Skip to content

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.

Answer

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));