I came across a block of code in a project and I find it hard to understand:
let isSelected = false;
const results = items.filter(Boolean).map(item => {
isSelected = !isSelected && id === item.id;
return {
id: item.id,
name: item.name
};
});
What's the line isSelected = !isSelected && id === item.id; before the return is trying to do?
Thanks.
It's a confusing way of, while mapping through the array, also setting isSelected to true if any of the elements in the array match the ID.
An equivalent approach would be
const truthyItems = items.filter(Boolean);
const results = truthyItems.map(item => ({
id: item.id,
name: item.name
}));
const isSelected = truthyItems.some(item => item.id === id);
Side-effects inside a .map callback are usually a bit of a code smell.