Javascript - How Do I Remove Objects From An Array That Contain A Specific String?
My array has several objects. Some of the objects contain a specific string, if the object contains this specific string I want it to be removed from the array. I tried to use a wh
Solution 1:
You can get the result using Array.filter
const value = [
{name: "Timmy", status: "Smelly"},
{name: "Tiffany", status: "Clean"},
{name: "Kyle", status: "Smelly"},
{name: "Space-man", status: "Clean"},
{name: "Soap-man", status: "Clean"}
];
const result = value.filter((item) => item.status !== 'Smelly');
console.log(result);
Solution 2:
Use filter as:
let myArray = [
{name: "Timmy", status: "Smelly"},
{name: "Tiffany", status: "Clean"},
{name: "Kyle", status: "Smelly"},
{name: "Space-man", status: "Clean"},
{name: "Soap-man", status: "Clean"},
]
let result = myArray.filter(i => i.status !== 'Smelly');
console.log(result)
Solution 3:
If you like to kee the object reference of the array, you could iterate from the end of the array.
Array#slice
changes the indices if spliced from start.
let array = [{ name: "Timmy", status: "Smelly" }, { name: "Tiffany", status: "Clean" }, { name: "Kyle", status: "Smelly" }, { name: "Space-man", status: "Clean" }, { name: "Soap-man", status: "Clean" }],
i = array.length;
while (i--) if (array[i].status === `Smelly`) array.splice(i, 1);
console.log(array);
.as-console-wrapper { max-height: 100%!important; top: 0; }
Solution 4:
Just filter it
You can choose to create a new filtered array or replace the existing one
let myArray = [ {name: "Timmy", status: "Smelly"}, {name: "Tiffany", status: "Clean"}, {name: "Kyle", status: "Smelly"}, {name: "Space-man", status: "Clean"}, {name: "Soap-man", status: "Clean"}]
// filter into a new arrayconst cleanArray = myArray.filter(item => item.status !== "Smelly")
console.log(cleanArray)
// or replace:
myArray = myArray.filter(item => item.status !== "Smelly")
console.log(myArray)
Solution 5:
First of all you need to have a boolean in the while loop. So you can add a counter starting from 0 and run the loop while the counter is less than the length of the array .
Here is the code:
let myArray = [
{ name: "Timmy", status: "Smelly" },
{ name: "Tiffany", status: "Clean" },
{ name: "Kyle", status: "Smelly" },
{ name: "Space-man", status: "Clean" },
{ name: "Soap-man", status: "Clean" },
]
let counter = 0;
while (counter < myArray.length) {
let find = myArray.findIndex(i => i.status === `Smelly`);
if (find != -1) {
myArray.splice(find, 1);
} else {
counter++;
}
}
myArray.forEach(el =>console.log(el));
Post a Comment for "Javascript - How Do I Remove Objects From An Array That Contain A Specific String?"