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

79
Views
comparing two arrays to create a new array

This seems like a very straightforward problem but for the life of me, I can not get it sorted.

I want to compare two arrays and if the value of array2 is in array1 push it to a new array otherwise push a 0.

these are my arrays:

let arrayOne = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18];
let arrayTwo = [3, 4, 5, 8, 9, 10, 12, 13, 14, 15, 16];

desired outcome is

[0,0,3,4,5,0,0,8,9,10,11,12,13,14,15,16,0,0]

current attempt with obvious indices issues

let newArray = [];

for (let i=0; i < arrayOne.length; i++){
  if(arrayTwo.includes(i)) newArray.push(arrayTwo[i]);
  else newArray.push(0);
};

current result

[0, 0, 0, 8, 9, 10, 0, 0, 13, 14, 15, 16, undefined, undefined, undefined, undefined, undefined, 0]
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Issue with your approach is that you are searching for an index in arrayTwo

if(arrayTwo.includes(i)) newArray.push(arrayTwo[i]);

where i is the index not a value. That's why you are getting undefined values, because arrayTwo has less values then arrayOne, so index of arrayOne will not exists in arrayTwo.

Instead you should search for value in arrayTwo

for (let i=0; i < arrayOne.length; i++){
  let value = arrayOne[i];
  if(arrayTwo.includes(value)) newArray.push(value);
  else newArray.push(0);
};

If you check only for existence of the value in collection - use Set which designed exactly for this purpose.

let arrayOne = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18];
let values = new Set([3, 4, 5, 8, 9, 10, 12, 13, 14, 15, 16]);

const result = arrayOne.map(value => values.has(value) ? value : 0);
// => [0,0,3,4,5,0,0,8,9,10,11,12,13,14,15,16,0,0]
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!