💻 Tech
There’s a problem with the output. The objective of the code below is to have show=true for the numbers in data1 that don’t exist in data2. However, the output shows 0 with true as well apart from 2.
The problem with it is with the negation !data2.find(j => j === i). find operation returns the value if it exists; otherwise, it returns undefined. For numbers 1,2,4,5, they are returned as-is, and therefore, when negated, the value will be true. This is because those values are ‘truthy’. On the other hand, 2 doesn’t exist in the other array, that’s why it’s undefined and negated to false because undefined is ‘falsy’. With 0, it exists that’s why it’s returned as 0; however, 0 is falsy, so negating it will return true.
To resolve the issue, we can directly check for undefined value instead of negating the result. Solution: showList.push({i: i, show: data2.find(j => j === i) == undefined} as item);.
index.ts:
const data1: number[] = [ 0, 1, 2, 3, 4, 5]; // list of complete numbers
const data2: number[] = [ 0, 1, 2, 4, 5 ]; // list of existing numbers (3 is missing)
interface item { i: number, show: boolean}
let showList: item[] = [];
data1.forEach(i => {
showList.push({i: i, show: !data2.find(j => j === i)} as item);
});
console.log(showList);
output:
[
{ i: 0, show: true },
{ i: 1, show: false },
{ i: 2, show: false },
{ i: 3, show: true },
{ i: 4, show: false },
{ i: 5, show: false }
]