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

120
Views
Filter is not returning the first element of the array, even though console.log says it is

Given two arrays of integers, I want to make a new array with just the unique values of the two input arrays. I know there are a bunch of different ways to do this, but I'm interested in why the way I'm trying to do it is not working.

const arr1 = [1, 2, 3, 4, 5];
const arr2 = [2, 3, 1, 0, 5];

// combine both arrays
const combined = arr1.concat(arr2);

// sort combined array
combined.sort();

// fitler out elements identical to the preceding element
const result = combined.filter((el, i, a) => {

  if ( (el != a[i-1]) ) {
    console.log("return", el);
    return el;
  }
});

// print
console.log(result);

Even though zero is part of the combined array, the output is [1,2,3,4,5]. When I console.log it, I definitely see that my filter method is returning element zero, but for some reason it doesn't show up in the result array. What's wrong?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The lambda in the filter must return a boolean value (thruthy or falsy). 0 is considered falsy, so the value will not be in the result.

Maybe you don't need a loop after all: a Set weeds out the duplicate values.

const arr1 = [1, 2, 3, 4, 5];
const arr2 = [2, 3, 1, 0, 5];

// use Set
console.log(JSON.stringify([...new Set(arr1.concat(arr2))]));

// or filter with a lambda that returns true/false
const result = arr1.concat(arr2).sort().filter((val, i, a) => val !== a[i-1]);
console.log(JSON.stringify(result));

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!