Skip to content

JavaScript remove object from array by property | Example code

  • by

Use filter() method to remove objects from the array by property in JavaScript. The filter creates a new array so any other variables referring to the original array would not get the filtered data although the updated original variable Array.

myArray = myArray.filter(function(obj) {
    return obj.field !== 'money';
});

JavaScript remove object from the array by property

A simple example code removes all objects based on property value from the array.

<!DOCTYPE html>
<html>
<body>
  <script>
    const myarr = [
    {
      name: 'foo',
      school: 'hoo'
    },{
      name: 'foo',
      school: 'xooo'
    },{
      name: 'bar',
      school: 'xooo'
    }
    ];

    const filterArray = myarr.filter(obj => obj.name !== 'foo');
    console.log(filterArray)
  </script>
</body>
</html> 

Output:

JavaScript remove object from array by property

Using the lodash library:

var myArray = [
    {field: 'id', operator: 'eq', value: 'id'}, 
    {field: 'cStatus', operator: 'eq', value: 'cStatus'}, 
    {field: 'money', operator: 'eq', value: 'money'}
];
var newArray = _.remove(myArray, function(n) {
  return n.value === 'money';;
});

console.log(newArray);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js"></script

Output:

[
  {
    "field": "money",
    "operator": "eq",
    "value": "money"
  }
]

Remove Object from Array

You can use several methods to remove item(s) from an Array:

someArray.shift(); // first element removed

someArray = someArray.slice(1); // first element removed

someArray.splice(0, 1); // first element removed

someArray.pop(); // last element removed

someArray = someArray.slice(0, someArray.length - 1); // last element removed

someArray.length = someArray.length - 1; // last element removed

Using splice() method:

You can use the splice() method to remove the object from the array in place:

var idToRemove = 2;

for (var i = 0; i < array.length; i++) {
  if (array[i].id === idToRemove) {
    array.splice(i, 1);
    break; // Exit the loop once the item is removed
  }
}

console.log(array);

Choose the method that best suits your needs. The filter() method creates a new array without modifying the original, while the splice() method modifies the original array in place.

Comment if you have any doubts or suggestions on this Js object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *