-1

I have a JS Array as follows:

const cars = [
  {
    make   : "Toyota",
    model  : "Corolla",
    year   : 2022,
    active : "false"
  },
  {
    make   : "Tesla", 
    model  : "Model 3",
    year   : 2021,
    active : "true"
  }
];

if I use:

let filteredCars = cars.filter((cars) => {
    return cars.active == "true";
});

i then update filteredCars.active = "false"

does it update the cars array? or just filteredCars ?

The reason i ask is if i use index as the key to update the array won't it be the wrong index? it will be 1 in cars but 0 in filteredCars....

so, how do I ensure that cars is updated correctly?

7
  • 2
    This is very confusing. You're shadowing variables (cars the array and cars the filter predicate parameter), making an assignment (active="true") where you probably meant a comparison using ==, referring to the undefined active variable (you probably meant cars.active), and assigning a random property to an array (filteredCars.active="false"). Please edit your question for clarity Commented yesterday
  • 2
    If I understand correctly, you're asking if the filtered array updates automatically when items in the original array change. The answer is "no", Array.prototype.filter() runs once at call time. How you would implement such a thing is a pretty broad topic Commented yesterday
  • hi Phil, no, the opposite - when the filtered array is editied does the original array get updated? Commented yesterday
  • 2
    "i then update filteredCars.active="false"" 👈 this doesn't make sense. Did you mean filteredCars[0].active = "false" or similar? If so, then that will update the same object reference in each array. But that doesn't really align with what you're asking after that. Commented yesterday
  • yes, sorry filteredCars[0].active="false" . will cars[0] be updated or cars[1] ? Commented yesterday

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.