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

151
Visualizações
match two Arrays and keep order of both equal

So I have two arrays with the same length, but not entirely the same data as follows:

Array1: [{name: john, num: 030}, {name: david, num: 130}, {name: john, num: 200}, {name: jane, num: 500}]
Array2: [{name: john, num: 030}, {name: david, num: 130}, {name: jane, num: 500}, {name: '', num: ''}]

Array2 only has element where num matches Array1 num

Is there a way to make sure that these two arrays match their indexes even if the data does not match

for example, their index will look like this

Array1: [{name: john, num: 030}, {name: david, num: 130}, {name: john, num: 200}, {name: jane, num: 500}]
Array2: [{name: james, num: 030}, {name: frank, num: 130}, {name: '', num: ''},  {name: kate, num: 500},]

This means they match by index, and order is maintained. The main goal is that Array2 maintains the order of Array1.

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

0

According to the description seen in the question, list two logics

  1. The value of attribute num is unique in each array
  2. The only exception is an empty string

I implemented it according to the above logic, you can see if it helps you, if the logic does not meet your actual needs, you can provide more details and clear logic, I will adjust it

const array1 = [{name: 'john', num: '030'}, {name: 'david', num: '130'}, {name: 'john', num: '200'}, {name: 'jane', num: '500'}];

let array2 = [{name: 'david', num: '130'}, {name: 'jane', num: '500'}, {name: 'john', num: '030'}, {name: '', num: ''}];

const originalLength = array2.length;
const originalArr = array2.slice(0, originalLength);
array2.length = originalLength * 2;

const provide = (arr, field, index) => {
  let result = arr.filter(a => a[field] == array1[index][field]);
  if(result.length == 0){
    result = arr.filter(a => a[field] == '');
  }
  return result[0];
};

for(let i=0; i<array1.length ; i++)
{
  const item = provide(originalArr, 'num', i);
  array2[i] = item;
}

array2.length = originalLength;
console.log(JSON.stringify(array2));

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