0

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.