3

I have an array of objects

let people = [{

  Name: 'Bob',

  Age: '45',
},
{
  Name: 'Jim',

  Age: '45',
}

];

let person = people.filter(person => person.Name=== 'Bob') 

This returns Bob but how do I delete him?

This only seems to delete a property

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete

so it seems I need an index or maybe there is a better ES6 way?

2
  • you wanna remove an element from array ? splice() ?? Commented Aug 7, 2018 at 10:19
  • 2
    just flip it around - let person = people.filter(person => person.Name!== 'Bob'). Filter will only return elements that return false to your condition and ignore the others. Commented Aug 7, 2018 at 10:23

4 Answers 4

13

You can use splice and findIndex methods and remove specific object from an array.

let people = [{"Name":"Bob","Age":"45"},{"Name":"Jim","Age":"45"}]

people.splice(people.findIndex(({Name}) => Name == "Bob"), 1);
console.log(people)

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

1 Comment

This works also as above answer did not work for me people.splice(people.findIndex((foo) => foo.Name == "Bob"), 1); console.log(people)
4

To remove bob simply do the opposite equality check

let person = people.filter(person => person.Name !== 'Bob') 

To mutate the original array, you can use splice

const index = people.findIndex(person => person.Name === 'Bob');
if (index > -1) {
   people.splice(index, 1);
}

2 Comments

Sorry I mean from the original object, not remove I suppose I mean delete.
people = people.filter(person => person.Name !== 'Bob') ;
1
  1. Find the index of the object where name = "Bob"
  2. Remove it from the array using splice()

people.splice(people.findIndex(({Name}) => Name == "Bob"), 1);

Comments

0

Just simply change your code in the filter section from "===" to "!==" to delete it.

  let people = [
    {
      Name: "Bob",

      Age: "45",
    },
    {
      Name: "Jim",

      Age: "45",
    },
  ];

  let person = people.filter((person) => person.Name !== "Bob");
  console.log(person);

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.