[javascript] Remove Object from Array using JavaScript

How can I remove an object from an array? I wish to remove the object that includes name Kristian from someArray. For example:

someArray = [{name:"Kristian", lines:"2,5,10"},
             {name:"John", lines:"1,19,26,96"}];

I want to achieve:

someArray = [{name:"John", lines:"1,19,26,96"}];

This question is related to javascript arrays

The answer is


Performance

Today 2021.01.27 I perform tests on MacOs HighSierra 10.13.6 on Chrome v88, Safari v13.1.2 and Firefox v84 for chosen solutions.

Results

For all browsers:

  • fast/fastest solutions when element not exists: A and B
  • fast/fastest solutions for big arrays: C
  • fast/fastest solutions for big arrays when element exists: H
  • quite slow solutions for small arrays: F and G
  • quite slow solutions for big arrays: D, E and F

enter image description here

Details

I perform 4 tests cases:

  • small array (10 elements) and element exists - you can run it HERE
  • small array (10 elements) and element NOT exists - you can run it HERE
  • big array (milion elements) and element exists - you can run it HERE
  • big array (milion elements) and element NOT exists - you can run it HERE

Below snippet presents differences between solutions A B C D E F G H I

_x000D_
_x000D_
function A(arr, name) {
  let idx = arr.findIndex(o => o.name==name);
  if(idx>=0) arr.splice(idx, 1);
  return arr;
}


function B(arr, name) {
  let idx = arr.findIndex(o => o.name==name);
  return idx<0 ? arr : arr.slice(0,idx).concat(arr.slice(idx+1,arr.length));
}


function C(arr, name) {
  let idx = arr.findIndex(o => o.name==name);
  delete arr[idx];
  return arr;
}


function D(arr, name) {
  return arr.filter(el => el.name != name);
}


function E(arr, name) {
  let result = [];
  arr.forEach(o => o.name==name || result.push(o));
  return result;
}


function F(arr, name) {
  return _.reject(arr, el => el.name == name);
}


function G(arr, name) {
  let o = arr.find(o => o.name==name);
  return _.without(arr,o);
}


function H(arr, name) {
  $.each(arr, function(i){
      if(arr[i].name === 'Kristian') {
          arr.splice(i,1);
          return false;
      }
  });
  return arr;
}


function I(arr, name) {
  return $.grep(arr,o => o.name!=name);
}








// Test
let test1 = [   
    {name:"Kristian", lines:"2,5,10"},
    {name:"John", lines:"1,19,26,96"},  
];

let test2 = [   
    {name:"John3", lines:"1,19,26,96"},
    {name:"Kristian", lines:"2,5,10"},
    {name:"John", lines:"1,19,26,96"},
  {name:"Joh2", lines:"1,19,26,96"},
];

let test3 = [   
    {name:"John3", lines:"1,19,26,96"},
    {name:"John", lines:"1,19,26,96"},
  {name:"Joh2", lines:"1,19,26,96"},
];

console.log(`
Test1: original array from question
Test2: array with more data
Test3: array without element which we want to delete
`);

[A,B,C,D,E,F,G,H,I].forEach(f=> console.log(`
Test1 ${f.name}: ${JSON.stringify(f([...test1],"Kristian"))}
Test2 ${f.name}: ${JSON.stringify(f([...test2],"Kristian"))}
Test3 ${f.name}: ${JSON.stringify(f([...test3],"Kristian"))}
`));
_x000D_
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
  
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"> </script>
  
This shippet only presents functions used in performance tests - it not perform tests itself!
_x000D_
_x000D_
_x000D_

And here are example results for chrome

enter image description here


There seems to be an error in your array syntax so assuming you mean an array as opposed to an object, Array.splice is your friend here:

someArray = [{name:"Kristian", lines:"2,5,10"}, {name:"John", lines:"1,19,26,96"}];
someArray.splice(1,1)

This Concepts using Kendo Grid

var grid = $("#addNewAllergies").data("kendoGrid");

var selectedItem = SelectedCheckBoxList;

for (var i = 0; i < selectedItem.length; i++) {
    if(selectedItem[i].boolKendoValue==true)
    {
        selectedItem.length= 0;
    }
}

This is a function that works for me:

function removeFromArray(array, value) {
    var idx = array.indexOf(value);
    if (idx !== -1) {
        array.splice(idx, 1);
    }
    return array;
}

If you want to remove all occurrences of a given object (based on some condition) then use the javascript splice method inside a for the loop.

Since removing an object would affect the array length, make sure to decrement the counter one step, so that length check remains intact.

var objArr=[{Name:"Alex", Age:62},
  {Name:"Robert", Age:18},
  {Name:"Prince", Age:28},
  {Name:"Cesar", Age:38},
  {Name:"Sam", Age:42},
  {Name:"David", Age:52}
];

for(var i = 0;i < objArr.length; i ++)
{
  if(objArr[i].Age > 20)
  {
    objArr.splice(i, 1);
    i--;  //re-adjust the counter.
  }
}

The above code snippet removes all objects with age greater than 20.


This answer

for (var i =0; i < someArray.length; i++)
   if (someArray[i].name === "Kristian") {
      someArray.splice(i,1);
   }

is not working for multiple records fulfilling the condition. If you have two such consecutive records, only the first one is removed, and the other one skipped. You have to use:

for (var i = someArray.length - 1; i>= 0; i--)
   ...

instead .


I have made a dynamic function takes the objects Array, Key and value and returns the same array after removing the desired object:

function removeFunction (myObjects,prop,valu)
        {
             return myObjects.filter(function (val) {
              return val[prop] !== valu;
          });

        }

Full Example: DEMO

var obj = {
            "results": [
              {
                  "id": "460",
                  "name": "Widget 1",
                  "loc": "Shed"
              }, {
                  "id": "461",
                  "name": "Widget 2",
                  "loc": "Kitchen"
              }, {
                  "id": "462",
                  "name": "Widget 3",
                  "loc": "bath"
              }
            ]
            };


        function removeFunction (myObjects,prop,valu)
        {
             return myObjects.filter(function (val) {
              return val[prop] !== valu;
          });

        }


console.log(removeFunction(obj.results,"id","460"));

You could use array.filter().

e.g.

        someArray = [{name:"Kristian", lines:"2,5,10"},
                     {name:"John", lines:"1,19,26,96"}];

        someArray = someArray.filter(function(returnableObjects){
               return returnableObjects.name !== 'Kristian';
        });

        //someArray will now be = [{name:"John", lines:"1,19,26,96"}];

Arrow functions:

someArray = someArray.filter(x => x.name !== 'Kristian')

someArray = jQuery.grep(someArray , function (value) {
        return value.name != 'Kristian';
});

I recommend using lodash.js or sugar.js for common tasks like this:

// lodash.js
someArray = _.reject(someArray, function(el) { return el.Name === "Kristian"; });

// sugar.js
someArray.remove(function(el) { return el.Name === "Kristian"; });

in most projects, having a set of helper methods that is provided by libraries like these is quite useful.


Returns only objects from the array whose property name is not "Kristian"

var noKristianArray = $.grep(someArray, function (el) { return el.name!= "Kristian"; });


Demo:

_x000D_
_x000D_
 var someArray = [_x000D_
                {name:"Kristian", lines:"2,5,10"},_x000D_
                {name:"John", lines:"1,19,26,96"},_x000D_
                {name:"Kristian", lines:"2,58,160"},_x000D_
                {name:"Felix", lines:"1,19,26,96"}_x000D_
                ];_x000D_
    _x000D_
var noKristianArray = $.grep(someArray, function (el) { return el.name!= "Kristian"; });_x000D_
_x000D_
console.log(noKristianArray);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_


Here is an example with map and splice

_x000D_
_x000D_
const arrayObject = [
  { name: "name1", value: "value1" },
  { name: "name2", value: "value2" },
  { name: "name3", value: "value3" },
];

let index = arrayObject.map((item) => item.name).indexOf("name1");
if (index > -1) {
  
  arrayObject.splice(index, 1);
  console.log("Result", arrayObject);
  

}
_x000D_
_x000D_
_x000D_


How about this?

$.each(someArray, function(i){
    if(someArray[i].name === 'Kristian') {
        someArray.splice(i,1);
        return false;
    }
});

You can use map function also.

someArray = [{name:"Kristian", lines:"2,5,10"},{name:"John",lines:"1,19,26,96"}];
newArray=[];
someArray.map(function(obj, index){
    if(obj.name !== "Kristian"){
       newArray.push(obj);
    }
});
someArray = newArray;
console.log(someArray);

I guess the answers are very branched and knotted.

You can use the following path to remove an array object that matches the object given in the modern JavaScript jargon.


coordinates = [
    { lat: 36.779098444109145, lng: 34.57202827508546 },
    { lat: 36.778754712956506, lng: 34.56898128564454 },
    { lat: 36.777414146732426, lng: 34.57179224069215 }
];

coordinate = { lat: 36.779098444109145, lng: 34.57202827508546 };

removeCoordinate(coordinate: Coordinate): Coordinate {
    const found = this.coordinates.find((coordinate) => coordinate == coordinate);
    if (found) {
      this.coordinates.splice(found, 1);
    }
    return coordinate;
  }

Simplest solution would be to create a map that stores the indexes for each object by name, like this:

//adding to array
var newPerson = {name:"Kristian", lines:"2,5,10"}
someMap[ newPerson.name ] = someArray.length;
someArray.push( newPerson );

//deleting from the array
var index = someMap[ 'Kristian' ];
someArray.splice( index, 1 );

ES2015

let someArray = [
               {name:"Kristian", lines:"2,5,10"},
               {name:"John", lines:"1,19,26,96"},
               {name:"Kristian", lines:"2,58,160"},
               {name:"Felix", lines:"1,19,26,96"}
            ];

someArray = someArray.filter(person => person.name != 'John');

It will remove John!


Vote for the UndercoreJS for simple work with arrays.

_.without() function helps to remove an element:

 _.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
    => [2, 3, 4]

If you wanna access and remove object of an array simply you can try something like this.

_x000D_
_x000D_
// inside some function_x000D_
_x000D_
let someArray = [ {"ColumnName" : "a", "PropertySerno" : 100005,"UpdateType" : 1},_x000D_
                  {"ColumnName" : "b", "PropertySerno" : 100202,"UpdateType" : 1,_x000D_
        "ShowRemoveButton" : true} ];_x000D_
        _x000D_
        for (let item of someArray) {_x000D_
          delete item.ShowRemoveButton;_x000D_
        }_x000D_
        console.log(item.outputMappingData.Data);_x000D_
        _x000D_
//output will be like that = [ {"ColumnName" : "a", "PropertySerno" : 100005,"UpdateType" : 1},_x000D_
//                             {"ColumnName" : "b", "PropertySerno" : 100202,"UpdateType" : 1 }];_x000D_
        
_x000D_
_x000D_
_x000D_


You could also try doing something like this:

var myArray = [{'name': 'test'}, {'name':'test2'}];
var myObject = {'name': 'test'};
myArray.splice(myArray.indexOf(myObject),1);

Use splice function on arrays. Specify the position of the start element and the length of the subsequence you want to remove.

someArray.splice(pos, 1);

The clean solution would be to use Array.filter:

var filtered = someArray.filter(function(el) { return el.Name != "Kristian"; }); 

The problem with this is that it does not work on IE < 9. However, you can include code from a Javascript library (e.g. underscore.js) that implements this for any browser.


You could also use some:

someArray = [{name:"Kristian", lines:"2,5,10"},
             {name:"John", lines:"1,19,26,96"}];

someArray.some(item => { 
    if(item.name === "Kristian") // Case sensitive, will only remove first instance
        someArray.splice(someArray.indexOf(item),1) 
})

With ES 6 arrow function

let someArray = [
                 {name:"Kristian", lines:"2,5,10"},
                 {name:"John", lines:"1,19,26,96"}
                ];
let arrayToRemove={name:"Kristian", lines:"2,5,10"};
someArray=someArray.filter((e)=>e.name !=arrayToRemove.name && e.lines!= arrayToRemove.lines)

Use javascript's splice() function.

This may help: http://www.w3schools.com/jsref/jsref_splice.asp


splice(i, 1) where i is the incremental index of the array will remove the object. But remember splice will also reset the array length so watch out for 'undefined'. Using your example, if you remove 'Kristian', then in the next execution within the loop, i will be 2 but someArray will be a length of 1, therefore if you try to remove "John" you will get an "undefined" error. One solution to this albeit not elegant is to have separate counter to keep track of index of the element to be removed.


This is what I use.

Array.prototype.delete = function(pos){
    this[pos] = undefined;
    var len = this.length - 1;
    for(var a = pos;a < this.length - 1;a++){
      this[a] = this[a+1];
    }
    this.pop();
  }

Then it is as simple as saying

var myArray = [1,2,3,4,5,6,7,8,9];
myArray.delete(3);

Replace any number in place of three. After the expected output should be:

console.log(myArray); //Expected output 1,2,3,5,6,7,8,9

Your "array" as shown is invalid JavaScript syntax. Curly brackets {} are for objects with property name/value pairs, but square brackets [] are for arrays - like so:

someArray = [{name:"Kristian", lines:"2,5,10"}, {name:"John", lines:"1,19,26,96"}];

In that case, you can use the .splice() method to remove an item. To remove the first item (index 0), say:

someArray.splice(0,1);

// someArray = [{name:"John", lines:"1,19,26,96"}];

If you don't know the index but want to search through the array to find the item with name "Kristian" to remove you could to this:

for (var i =0; i < someArray.length; i++)
   if (someArray[i].name === "Kristian") {
      someArray.splice(i,1);
      break;
   }

EDIT: I just noticed your question is tagged with "jQuery", so you could try the $.grep() method:

someArray = $.grep(someArray,
                   function(o,i) { return o.name === "Kristian"; },
                   true);

Although this is probably not that appropriate for this situation I found out the other day that you can also use the delete keyword to remove an item from an array if you don't need to alter the size of the array e.g.

var myArray = [1,2,3];

delete myArray[1];

console.log(myArray[1]); //undefined

console.log(myArray.length); //3 - doesn't actually shrink the array down