Victor
Victor

Reputation: 75

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?

Upvotes: 0

Views: 511

Answers (1)

KooiInc
KooiInc

Reputation: 122966

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

Upvotes: 1

Related Questions