Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

140
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!