Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

327
Visualizações
JavaScript | How can I remove an element of an array using it's value instead of it's index?
const currentMaterialsId = [1,2,3,4,5]
        
        
        const materials = {
                        0: {
                            id: 1
                        },
                        1: {
                            id: 2
                        },
                        2: {
                            id: 3
                        },
                        3: {
                            id: 4
                        },
                        4: {
                            id: 5
                        }
                    }

I am trying to remove an element in the currenMaterialsId array but when I use the index of the materials object, things don't go as planned. If I use the id as the start number in splice, it still uses that number and searches for the matching index in the array instead of the value. Please help.

here's what I have at the moment.

let sortedMaterialIndex = currentMaterialsId.sort()
        sortedMaterialIndex.splice(materialIndex, 1)
        dispatch(removeElementCurrentMaterialsArray(selectedSheet, 
        sortedMaterialIndex))

ok I'm sorry it wasn't clear guys.

What I am trying to do is remove an element in currentMaterialsId that has the same value as the id in the object materials. However, when I use the id from materials as a starting number, for example

const materialId = dashboard.sheets[selectedSheet].materialProperties[materialIndex].id
currentMaterialsId.splice(materialId, 1)

it searches currentMaterialsId array for an index that matches the passed starting number(materialId), which is what I do not want.

so let's say I want to delete 2 from currentMaterialsId, could I use splice? and if I use splice, what should I pass as a starting number?

I hope this makes my question clearer. Thanks for the responses!

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

What I am trying to do is remove an element in currentMaterialsId that has the same value as the id in the object materials.

could I use splice?


You appear to be trying to do something like this:

so.js:

const materials = {
  '0': { id: 1 },
  '1': { id: 2 },
  '2': { id: 3 },
  '3': { id: 4 },
  '4': { id: 5 }
};

console.log(materials);

// id from materials
let i = 1;
console.log(i);
let id = materials[i].id;
console.log(id);

function removeMaterialsId(id, materialsId) {
    for (let i = 0; i < materialsId.length; i++) { 
        if (materialsId[i] === id) {
            materialsId.splice(i--, 1);
        }
    }
}

let materialsId = [];

// remove materialsId elements with id from materials
console.log();
materialsId = [ 1, 2, 3, 4, 5 ];
console.log(id, materialsId);
removeMaterialsId(id, materialsId);
console.log(materialsId);

// remove materialsId elements with id from materials
console.log();
materialsId = [ 1, 2, 2, 3, 4, 2, 5 ];
console.log(id, materialsId);
removeMaterialsId(id, materialsId);
console.log(materialsId);

$ node so.js

{
  '0': { id: 1 },
  '1': { id: 2 },
  '2': { id: 3 },
  '3': { id: 4 },
  '4': { id: 5 }
}
1
2

2 [ 1, 2, 3, 4, 5 ]
[ 1, 3, 4, 5 ]

2 [ 1, 2, 2, 3, 4, 2, 5 ]
[ 1, 3, 4, 5 ]

$ 
about 4 years ago · Juan Pablo Isaza Relatório

0

First off, perhaps you want to store your objects in an array, like this(?):

const materials = [
    {
        id: 1
    },
    {
        id: 2
    },
    {
        id: 3
    },
    {
        id: 4
    },
    {
        id: 5
    }
];

Then you can remove from array using filter:

const materialToRemove = { id: 1 }

const materialsWithOneRemoved = materials
    .filter(material => material.id !== materialToRemove.id);

Note that filter creates a new array, it does not change the existing array. You can however overwrite the existing array with a new one if you want to:

// materials like above, but with let instead of const
let materials = ...

const materialToRemove = { id: 1 }

materials = materials
    .filter(material => material.id !== materialToRemove.id);

If you want to have your objects in an object like you have in your question, you need to first convert it to an array before you can filter. You can do that using e.g. Object.values.

about 4 years ago · Juan Pablo Isaza Relatório

0

Your question is far from clear, but indexOf may be a solution:

const sortedMaterialIndex = currentMaterialsId.sort();
const index = sortedMaterialIndex.indexOf(materialIndex);
if (index > -1) {
  sortedMaterialIndex.splice(index, 1);
}

See How can I remove a specific item from an array?

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda