Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

170
Views
How to change all array while updating one element in javascript?

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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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}));
about 4 years ago · Juan Pablo Isaza Report

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
  }
});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!