简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM