605

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"}];
  • 1
    possible duplicate of How do I remove an object from an array with JavaScript? – Quentin Apr 5 '12 at 8:11
  • 3
    FYI I have rolled back the edit on this question so the array syntax is wrong again, and all of these answers are in context. – Dunhamzzz Apr 5 '12 at 8:45
  • 2
    And then the array syntax was "corrected" (twice) again, so that the answers are no longer in context. – Teepeemm Oct 28 '15 at 0:12
  • 5
    How does the syntax error help make some answers make sense? – Samy Bencherif May 17 '16 at 21:10
  • 2
    @SamyBencherif - Some of the answers explicitly address the syntax error in the original version of the question, so if you remove that syntax error those answers are now talking about something that doesn't exist. – nnnnnn Nov 2 '16 at 1:17

29 Answers 29

847

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

//1
someArray.shift(); // first element removed
//2
someArray = someArray.slice(1); // first element removed
//3
someArray.splice(0, 1); // first element removed
//4
someArray.pop(); // last element removed
//5
someArray = someArray.slice(0, a.length - 1); // last element removed
//6
someArray.length = someArray.length - 1; // last element removed

If you want to remove element at position x, use:

someArray.splice(x, 1);

Or

someArray = someArray.slice(0, x).concat(someArray.slice(-x));

Reply to the comment of @chill182: you can remove one or more elements from an array using Array.filter, or Array.splice combined with Array.findIndex (see MDN), e.g.

// non destructive filter > noJohn = John removed, but someArray will not change
let someArray = getArray();
let noJohn = someArray.filter( el => el.name !== "John" ); 
log("non destructive filter > noJohn = ", format(noJohn));
log(`**someArray.length ${someArray.length}`);

// destructive filter/reassign John removed > someArray2 =
let someArray2 = getArray();
someArray2 = someArray2.filter( el => el.name !== "John" );
log("", "destructive filter/reassign John removed > someArray2 =", 
  format(someArray2));
log(`**someArray2.length ${someArray2.length}`);

// destructive splice /w findIndex Brian remains > someArray3 =
let someArray3 = getArray();
someArray3.splice(someArray3.findIndex(v => v.name === "Kristian"), 1);
someArray3.splice(someArray3.findIndex(v => v.name === "John"), 1);
log("", "destructive splice /w findIndex Brian remains > someArray3 =", 
  format(someArray3));
log(`**someArray3.length ${someArray3.length}`);

// Note: if you're not sure about the contents of your array, 
// you should check the results of findIndex first
let someArray4 = getArray();
const indx = someArray4.findIndex(v => v.name === "Michael");
someArray4.splice(indx, indx >= 0 ? 1 : 0);
log("", "check findIndex result first > someArray4 (nothing is removed) > ",
  format(someArray4));
log(`**someArray4.length (should still be 3) ${someArray4.length}`);

function format(obj) {
  return JSON.stringify(obj, null, " ");
}

function log(...txt) {
  document.querySelector("pre").textContent += `${txt.join("\n")}\n`
}

function getArray() {
  return [ {name: "Kristian", lines: "2,5,10"},
           {name: "John", lines: "1,19,26,96"},
           {name: "Brian", lines: "3,9,62,36"} ];
}
<pre>
**Results**

</pre>

| improve this answer | |
  • 2
    @Klemzy didnt you mean not by index ? by value ...? – Royi Namir Apr 5 '12 at 8:24
  • 364
    The original question asked how to remove the object with the name="Kristian" from the array. Your answer assumes it's the first item in the array but what if Kristin is not in the first item? Then your answer doesn't work. – Rochelle C Oct 17 '12 at 15:29
  • 8
    @chill182: it's not a specific answer, but a more general one. From it, you should be able to infer the method to remove elements. If you want to remove element at position x ... may be a hint for removing other than first elements, right? – KooiInc Oct 17 '12 at 15:47
  • 6
    The splice function was helpful to me, but you shouldn't have re-assigned someArray. This will result in someArray containing the removed item, instead of it containing the resulting array with the item removed. – Kenn Cal Jan 2 '14 at 6:10
  • 1
    You should check the findIndex result before using it in splice. If there are no elements in the array that match the condition findIndex will return -1and putting this directly into splice will result in an arbitraty deletion of the last element in the array. – jdnz Feb 19 '20 at 10:06
180

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.

| improve this answer | |
  • 11
    This however will remove all the occurrences found, not only the first one – Flavien Volken Jul 12 '16 at 6:49
  • 7
    And it will return a new array instead of modifying the original one. Depending on the use case, this may or may not be what you want. – Jochie Nabuurs Dec 13 '17 at 10:53
  • 1
    @JochieNabuurs it is indeed a new array. However, the object remains the same. You can still modify each object's value and it will reflect on the original array's object. – DriLLFreAK100 Jan 23 '19 at 3:46
  • 5
    To the point about this returning a new array, just changing the solution to someArray = someArray.filter(function(el) { return el.Name != "Kristian"; }); addresses that, no? – hBrent Feb 11 '19 at 23:08
  • It will work, doubtless. But if you are concerning about memory management it will create a new object anyway. I don't wanna me picky, this is gonna work for quite any case. But if for any reason you are dealing with a really large array, you should handle removing elements using the same object. – Luciano Camilo Oct 24 '20 at 14:30
134

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.

| improve this answer | |
  • 13
    I think the underscore example is slightly off. Should be someArray = _.reject(someArray, function(el) { return el.Name === "Kristian"; }); – Andy Ford Dec 20 '13 at 20:11
  • 8
    If you don't want to use underscore.js or sugar.js, you can do this someArray = someArray.filter(function(e) { return e.Name !== "Kristian"; }); – BenR May 13 '14 at 21:04
  • 1
    another thing i want, There will be separate buttons for every object in array. if i want to delete that particular object in the array button clicked. how to do it . i have used angular js ng-repeat to generate items. can you help me – Thilak Raj Jan 21 '16 at 4:32
  • 6
    Going to go against the grain here; suggesting one include an entire library for the simple purpose of removing items from objects (which js cleanly supports out of the box, as the accepted answer shows) is poor form. It adds unnecessary weight and complexity to your code unless you already need it for the more powerful functionality the library provides. – Josh Doebbert Aug 4 '16 at 15:26
  • 5
    For simple operation , i will never recommend to include library – Munna Bhakta Jan 31 '19 at 7:27
94

How about this?

$.each(someArray, function(i){
    if(someArray[i].name === 'Kristian') {
        someArray.splice(i,1);
        return false;
    }
});
| improve this answer | |
  • 8
    Won't that cause an error because $.each() caches the array length before looping so if you remove an element $.each() will run past the end of the (now shorter) array. (So then someArray[i] will be undefined and undefined.name will crash.) – nnnnnn Jul 2 '13 at 11:09
  • 5
    Then add a 'return false' after the splice. – Allan Taylor Jul 3 '13 at 13:43
  • 21
    this is not javascript. -1 – onionpsy Oct 26 '15 at 17:02
  • 23
    Please note that this answer requires jQuery – Clarkey Mar 4 '16 at 14:52
75

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);
| improve this answer | |
  • Why did they add the overload? Surely you could have just put != "Kristian". What purpose does the overload serve? – markthewizard1234 Oct 13 '17 at 15:56
  • @markthewizard1234 - Do you mean the "invert" Boolean argument in $.grep()? It doesn't add much in this example, where yes, I could've put !=, but in other cases you might already have a function defined that happens to do the opposite test to what you want to grep, so then rather than defining an additional function you can just use that overload to invert the results. – nnnnnn Oct 14 '17 at 0:02
  • Ah, so if you had a wrapper function containing the grep you could set the boolean as a parameter. Got it thanks! – markthewizard1234 Oct 16 '17 at 10:25
  • @markthewizard1234 - You could, but that's not what I had in mind: imagine you had function isEven(num) { return num%2===0 }. You could use $.grep(someArray, isEven) to get just the even numbers from the array, or $.grep(someArray, isEven, true) to do the opposite and get the non-even values. – nnnnnn Oct 16 '17 at 10:52
73

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!

| improve this answer | |
  • 6
    Man... Coming from java, I'm highgly confused that such a basic thing to do requires filtering of a list... wtf. This is the most accurate answer to OPs question I read so far. – codepleb Jan 14 '18 at 21:16
  • Yes, this is a good approach. Though it will also work prior to ES2015(ES6). The filter function has been available since version 5.1(2011) ecma-international.org/ecma-262/5.1/#sec-15.4.4.20 – user3777549 Nov 25 '18 at 21:29
51

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')
| improve this answer | |
  • another thing i want, There will be separate buttons for every object in array. if i want to delete that particular object in the array button clicked. how to do it . i have used angular js ng-repeat to generate items. can you help me – Thilak Raj Jan 21 '16 at 4:32
  • daCoda what if you have two conditions? – Malcolm Salvador May 12 '17 at 3:11
  • @MalcolmSalvador say for example if you have another conditions you can write this like below and continue with different && or || operator according to your need. someArray = someArray.filter(function(returnableObjects){ return returnableObjects.name !== 'Kristian' && cond2Query.age >= 22; }); – Biswajit Panday Apr 1 '20 at 6:32
20

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"));
| improve this answer | |
16

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;
}
| improve this answer | |
  • another thing i want, There will be separate buttons for every object in array. if i want to delete that particular object in the array button clicked. how to do it . i have used angular js ng-repeat to generate items. can you help me – Thilak Raj Jan 21 '16 at 4:33
12

You could also try doing something like this:

var myArray = [{'name': 'test'}, {'name':'test2'}];
var myObject = {'name': 'test'};
myArray.splice(myArray.indexOf(myObject),1);
| improve this answer | |
  • 2
    myArray.indexOf(myObject) returns -1, because no item was reference-equal to myObject. so splice() removes the -1th element in the array, which in this case is {'name':'test2'}! – Birchlabs Sep 22 '20 at 10:05
11
someArray = jQuery.grep(someArray , function (value) {
        return value.name != 'Kristian';
});
| improve this answer | |
10

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);
| improve this answer | |
9

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]
| improve this answer | |
  • The best solution. Works with object arrays. – Azee Jul 9 '13 at 10:40
5

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)
| improve this answer | |
3

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 );
| improve this answer | |
  • I like this idea, but must also ask, what are the memory use limits for an idea like this as indexes are added? I have an array that I'd like to index on 2 different fields in the object, so I'd have 2 maps in addition to the original source array. Is this a small price to pay for lookup speed or is there a solution that would be more efficient with memory? – Brad G. Feb 2 '15 at 0:53
3

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
| improve this answer | |
3

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.

| improve this answer | |
3

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 .

| improve this answer | |
2

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)
| improve this answer | |
2

Use javascript's splice() function.

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

| improve this answer | |
2

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);
| improve this answer | |
  • 1
    But if you want to iterate through the array, isn't it better to use forEach ? – corse32 May 9 '17 at 2:13
2

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) 
})
| improve this answer | |
2

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
| improve this answer | |
2

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;
  }
| improve this answer | |
1

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.

| improve this answer | |
1

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

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


Demo:

 var 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"}
                ];
			 
var noKristianArray = $.grep(someArray, function (el) { return el.name!= "Kristian"; });

console.log(noKristianArray);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

| improve this answer | |
1

Here is an example with map and splice

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);
  

}

| improve this answer | |
0

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;
    }
}
| improve this answer | |
-1

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

// inside some function

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

| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.