2

I need to have always only one element true in array.

Supposed I have an array

let data = [
  { letter: "a", id: 1, bool: false },
  { letter: "b", id: 2, bool: false },
  { letter: "c", id: 3, bool: false},
  { letter: "d", id: 4, bool: false },
];

every time I click on an element I need to change it to true while all other to false. I have a function

const updatedArray = data.map((item) => {
  if (item.id === id) {
    return {
      ...item,
      bool: true,
    };
  }
  return item;
});

But it works as a toggle for clicked element.

2 Answers 2

3

Your problem is here: return item;,you are actually returning the previous value and just updating the bool property of item which has the same id as id variable, but you need to toggle the bool property of all the items, you can acheive your goal like this:

const updatedArray = array.map((item) => ({...item, bool: item.id === id}));
Sign up to request clarification or add additional context in comments.

Comments

0

You need to also set the item's bool to false if it is not the selected item, not just set the selected item's bool to true. This should work:

const id = 3 (clicked item)
const updatedArray = array.map(item => {
  if (item.id === id) {
    return {
      ...item,
      bool: true
    };
  }
  return {
    ...item,
    bool: false
  }
});

2 Comments

Please be DRY - There is NEVER a reason to use IF to set a bool
I just modified the OP's code.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.