0

I am trying to remove an object from an array but it I dont know what I am doing wrong.

I have this array declared:

listA: [
       { title: 'Food', value: 'Patato' },
       { title: 'Drink', value: 'Cola' },
       { title: 'Desert', value: 'Cheesecake' },
       ],

I am trying to remove the object where its value is 'Cola', what I have tried is this:

  this.listA.filter(x => x.value !== 'Cola');

And it returns me the same list

I want to return this:

 listA: [
   { title: 'Food', value: 'Patato' },
   { title: 'Desert', value: 'Cheesecake' },
   ],
1
  • Note that the filter for !== is different than !=. This can catch you out if you think you're comparing numbers but you're actually comparing a number and a string representation of a number! Commented Aug 23, 2024 at 12:01

4 Answers 4

3

Your code should be filtering just fine, I think the issue here is that filter does not modify the original array, it returns a new array with the filtered results. If you want it to overwrite the original array, you'll need to say this.listA = this.listA.filter(...)

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

1 Comment

Thank you, it works!!
1
const listA = [
  { title: "Food", value: "Patato" },
  { title: "Drink", value: "Cola" },
  { title: "Desert", value: "Cheesecake" },
];

const result = listA.filter((obj) => obj.value !== 'Cola');

Comments

1

Looks like you need to do something like

this.listA = this.listA.filter(x => x.value !== 'Cola')

The filter method is immutable hence the original array isn't changed

Comments

0

As a complement to https://stackoverflow.com/a/70688107/6316468, here is what filter does under the hood (the original array this remains untouched):

var xs = [1, 2, 3, 4];
var ys = filter.call(
  xs, x => x % 2
);
console.log(
  "xs = [", xs.join(), "]"
);
console.log(
  "ys = [", ys.join(), "]"
);

function filter(predicate) {
  var xs = []; // new array
  for (let x in this) {
    if (predicate(x)) {
      xs.push(x);
    }
  }
  return xs;
}

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.