Remove Object from Array using JavaScript
#1
I'm struggling with an issue in JavaScript where I need to remove an object from an array based on a specific property. In this case, I want to get rid of the object that contains the name 'Kristian'. Here's the array I'm working with:

Code:
lines: "2,5,10"
}, {
    name: "John",
    lines: "1,19,26,96"
}];

I've been trying to use the `filter()` method to achieve this, but I'm not sure I'm doing it correctly. Could someone provide a solution that would successfully remove the object where `name` is equal to 'Kristian'?
Reply
#2
You're on the right track using the `filter()` method. This method creates a new array with all elements that pass the test implemented by the provided function. You need to return `true` for all the elements you want to keep in the array. If the object's `name` property equals 'Kristian', you want to return `false` to exclude it.
Here's a snippet of code that should do what you want:

Code:
});

This will iterate over the `someArray` and keep every object that does not have a `name` property of 'Kristian'.
Reply
#3
Okay, I see how `filter()` works now. However, I'd like to use an arrow function for a more concise syntax. Also, would you mind showing me how I would write this in ES6, just to make sure I'm up to date?
Reply
#4
Certainly! Using an arrow function would simplify the syntax further. Here is how you would rewrite the code in ES6:


Remember that arrow functions provide a shorter syntax and also does not bind its own `this`, `arguments`, `super`, or `new.target`. These are all factors that can be useful depending on the context of the usage of the function.
Reply
#5
Alright, I've implemented your suggestion and it works as expected. I will now provide the full working code including the declaration of the array and the filter for anyone who might have the same question in the future.
Here's the full ES6-compatible code snippet:

Code:
lines: "2,5,10"
}, {
    name: "John",
    lines: "1,19,26,96"
}];
someArray = someArray.filter(item => item.name !== "Kristian");
console.log(someArray);

This code will log an array excluding the object with the name 'Kristian'. No additional modules or libraries are required for this code, as it uses native JavaScript ES6 features.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)