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

240
Visualizações
Delete array element based on elements in an array as index

Suppose I have an array as

let arr1 = [0,2] This is always sorted

Note: These elements in array represent indexes to be deleted from another array.

I have another array as:

let arrOvj = [1,4,6,7,21,17,12]

I want to delete element of arrObj, based on indexes present in arr1.

So after deletion expected OP should be,

[4,7,21,17,12].

So how can I achieve this.

I tried as:

for(let i=0;i<arr1.length;i++){
   arrObj.splice(arr1[i],1)
}

But this is giving incorrect result.

Example: If arr1=[0]

It deletes first two elements instead of deleting element at index 0 of arrObj.

What other alternative can I follow so it deletes from provided index value only

Please let me know if anyone need any further information.

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

0

You can loop backwards over the indices to delete so that elements will never be shifted into a location that has not been already processed.

let arr1 = [0,2] 
let arrOvj = [1,4,6,7,21,17,12]
for(let i = arr1.length - 1; i >= 0; i--) arrOvj.splice(arr1[i], 1);
console.log(arrOvj);

about 4 years ago · Juan Pablo Isaza Relatório

0

Other way of doing it is using the filter method on the array and removing out the corresponding indexes as follows:

let arrObj = [1,4,6,7,21,17,12]
let indexes = [0,2]

let newArr = arrObj.filter((ele, index) => !indexes.includes(index));

console.log(newArr);

about 4 years ago · Juan Pablo Isaza Relatório

0

You can use splice and reduceRight here.

let arr1 = [0, 2];
let arrOvj = [1, 4, 6, 7, 21, 17, 12];

arrOvj = arr1.reduceRight((a, c) => (a.splice(c, 1), a), arrOvj);

console.log(arrOvj);

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