1375

What is the difference between using the delete operator on the array element as opposed to using the Array.splice method?

For example:

myArray = ['a', 'b', 'c', 'd'];

delete myArray[1];
//  or
myArray.splice (1, 1);

Why even have the splice method if I can delete array elements like I can with objects?

Kamil Kiełczewski
  • 53,729
  • 20
  • 259
  • 241
lYriCAlsSH
  • 54,286
  • 10
  • 24
  • 20
  • 3
    For `.splice` in loops, have a look at this question: [Delete from array in javascript](http://stackoverflow.com/questions/9362412/delete-from-array-in-javascript). – Rob W Feb 20 '12 at 14:29
  • 6
    @andynormancx Yes, but this answer was posted just the day after, and got so many more votes - I'd say it's better written, that must be it. – Camilo Martin May 26 '13 at 12:43
  • @andynormancx — It doesn’t seem to be an exact duplicate. The question you linked is basically asking why deleting an element from an array (thus making it sparse) won’t reduce its length. This question is asking for the differences between `delete` and `Array.prototype.splice`. – chharvey Mar 03 '18 at 17:17
  • @chharvey agreed, more importantly though how can this question have been posted 9 years ago ! Makes me feel old to be back here commenting on it – andynormancx Mar 13 '18 at 08:48

27 Answers27

1744

delete will delete the object property, but will not reindex the array or update its length. This makes it appears as if it is undefined:

> myArray = ['a', 'b', 'c', 'd']
  ["a", "b", "c", "d"]
> delete myArray[0]
  true
> myArray[0]
  undefined

Note that it is not in fact set to the value undefined, rather the property is removed from the array, making it appear undefined. The Chrome dev tools make this distinction clear by printing empty when logging the array.

> myArray[0]
  undefined
> myArray
  [empty, "b", "c", "d"]

myArray.splice(start, deleteCount) actually removes the element, reindexes the array, and changes its length.

> myArray = ['a', 'b', 'c', 'd']
  ["a", "b", "c", "d"]
> myArray.splice(0, 2)
  ["a", "b"]
> myArray
  ["c", "d"]
Andy Hume
  • 36,376
  • 9
  • 41
  • 53
  • 76
    Actually, `delete` *does* remove the element, but does not reindex the array or update its length (which is already implied by the former since the length is always the highest index+1). – Felix Kling Jun 20 '12 at 18:11
  • 3
    JSlint doesn't like `delete myArray[0]` syntax saying "**Expected an operator and instead saw 'delete'.**" Using `splice` is recommended. – Eye Oct 11 '12 at 10:27
  • 24
    @Eye: Actually, JSLint is just complaining about the lack of a semicolon on the previous line. And you can’t really recommend one over the other, since they do completely different things… – Ry- Sep 10 '13 at 13:52
  • @CédricGuillemette: Because `splice` can also be used to insert elements. – Ry- Sep 10 '13 at 13:53
  • gotcha if you are going to remove multiple elements, as index of array changes http://stackoverflow.com/questions/9425009/remove-multiple-elements-from-array-in-javascript-jquery – vincentlcy Dec 07 '13 at 15:15
  • 4
    *"Delete in this case will only set the element as undefined:"* No, that is flatly incorrect. There's a fundamental difference between `delete myArray[0]` and `myArray[0] = undefined`. In the former case, the property is removed from the array object entirely. In the second case, the property remains, with the value `undefined`. – T.J. Crowder Feb 19 '17 at 10:33
  • I understand the distinction, thanks. But how can I prove that detail in the code example? Which ever way I try and inspect the array it appears the same. – Andy Hume Mar 03 '17 at 15:51
  • 1
    FYI, the Chrome dev tools shows the keyword `empty` instead of `undefined` to improve the distinction between an actually deleted (or uninitialized) array element versus an element that has the real value of `undefined`. Note that as I say this I mean it only *displays* as `empty`, and does not refer to a real value called `empty` (which does not exist). – chharvey Mar 03 '18 at 17:38
  • your_array = ['aa','bb','cc']; //-- exp. delete the first one or index 0 your_array.splice(0, 1); it print : ['bb','cc']; – Ruthe Oct 16 '18 at 08:11
  • is there any way to remove the empty elements from my array after using the delete method – Yazeed Zaid Sep 05 '20 at 11:10
343

Array.remove() Method

John Resig, creator of jQuery created a very handy Array.remove method that I always use it in my projects.

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

and here's some examples of how it could be used:

// Remove the second item from the array
array.remove(1);
// Remove the second-to-last item from the array
array.remove(-2);
// Remove the second and third items from the array
array.remove(1,2);
// Remove the last and second-to-last items from the array
array.remove(-2,-1);

John's website

Mohsen
  • 58,878
  • 30
  • 149
  • 175
  • 5
    +1 For Array.remove(). However it's not happy being passed string arguments (unlike most Array methods, eg `[1,2,3].slice('1'); // =[2,3]`), so it's safer to change it to `var rest = this.slice(parseInt(to || from) + 1 || this.length);` – Richard Inglis Jun 15 '12 at 15:10
  • I found that this was causing an asynchronous problem. Does the thread get given up before the this.push.apply() ? – thomas-peter Aug 23 '12 at 09:34
  • 1
    @tomwrong, there are no threads in javascript, and the function executes `this.push.apply(this, rest)`, then returns the value it returned – billy Apr 04 '13 at 12:00
  • 66
    This doesn’t answer the question at all. – Ry- Apr 28 '13 at 15:20
  • I think it would be more helpful to return the elements that were removed instead of the new count. – Daniel Lidström May 30 '13 at 07:17
  • 17
    Why not just use splice()? The name of this function, the parameter names and the results aren't obvious. My recommendation is to just use splice(index,length) - (see Andy Hume's answer) – auco May 31 '13 at 09:22
  • 3
    Function provided above works as explained, yet it creates unwanted side effects when iterating through array with `for(var i in array)` cycle. I've removed it and used splice instead. – alexykot Sep 27 '13 at 15:44
  • @auco Look at John's website in the link above. It can do negative values and remove single items with a single parameter. – Alex W Oct 29 '13 at 19:05
  • alexykot, got the same strange error as you did. Chrome console said there was some "range" error when a lib of mine iterated through the array with `for (var i in array)`. So I declared the John-remove function separately and not on `Array.prototype`. – Martin Andersson Dec 17 '13 at 17:44
  • If you want to iterate an array, you should use a for(i=0;i<.length all="" also="" are="" array="" arrays="" but="" enumerable="" exist="" extra="" false="" for="" former="" get="" in="" indices="" instead="" integers="" latter="" length="" methods="" not="" object="" objects="" of="" property="" prototype="" set="" the="" they="" to="" will="" won="" work="" you="" your=""> – dab Nov 26 '14 at 21:27
  • This does not remove multiple elements if they should be present. – lifebalance Jul 16 '16 at 07:13
  • MartinAndersson and alexykot - Lots of things cause issues when using `for...in` to loop through an Array's indices. That's because `for...in` is not a proper way to loop through Array indices :) `for...in` enumerates Object properties. Arrays may have more Object properties than just their indices. So if you're trying to loop through just indices and you're using `for...in` then you're doing it wrong. Use a sequential loop (e.g. `for (var i=0; i – BryanGrezeszak Jan 05 '18 at 17:12
  • Did he actually licensed a single function. JS community amazes me. – atilkan Apr 03 '18 at 11:36
  • this answer deserves more love, i come from python background and this way to do it feels just like home. thanks ! – Shantanu Bedajna May 30 '20 at 20:27
104

Because delete only removes the object from the element in the array, the length of the array won't change. Splice removes the object and shortens the array.

The following code will display "a", "b", "undefined", "d"

myArray = ['a', 'b', 'c', 'd']; delete myArray[2];

for (var count = 0; count < myArray.length; count++) {
    alert(myArray[count]);
}

Whereas this will display "a", "b", "d"

myArray = ['a', 'b', 'c', 'd']; myArray.splice(2,1);

for (var count = 0; count < myArray.length; count++) {
    alert(myArray[count]);
}
andynormancx
  • 12,430
  • 6
  • 33
  • 52
  • 11
    great example except the ambiguity in the second example by using 1,1 - the first 1 refers to the index in the array to start the splice, the second 1 is the number of elements to remove. So to remove 'c' from the original array, use `myArray.splice(2,1)` – iancoleman Jul 06 '12 at 06:33
71

I stumbled onto this question while trying to understand how to remove every occurrence of an element from an Array. Here's a comparison of splice and delete for removing every 'c' from the items Array.

var items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];

while (items.indexOf('c') !== -1) {
  items.splice(items.indexOf('c'), 1);
}

console.log(items); // ["a", "b", "d", "a", "b", "d"]

items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];

while (items.indexOf('c') !== -1) {
  delete items[items.indexOf('c')];
}

console.log(items); // ["a", "b", undefined, "d", "a", "b", undefined, "d"]
​
Troy Harvey
  • 2,243
  • 18
  • 18
14

From Core JavaScript 1.5 Reference > Operators > Special Operators > delete Operator :

When you delete an array element, the array length is not affected. For example, if you delete a[3], a[4] is still a[4] and a[3] is undefined. This holds even if you delete the last element of the array (delete a[a.length-1]).

f3lix
  • 27,786
  • 10
  • 63
  • 82
10

splice will work with numeric indices.

whereas delete can be used against other kind of indices..

example:

delete myArray['text1'];
Mahmoud Gamal
  • 72,639
  • 16
  • 129
  • 156
Gopal
  • 145
  • 1
  • 2
  • 9
    When you say 'any other kind of indices', you're not talking about arrays any more, but rather objects, which is what the OP is asking about. – Yi Jiang Jan 23 '11 at 16:58
  • 2
    @YiJiang: Arrays are Objects. Indizes are properties. There is no difference. – Bergi May 24 '12 at 22:55
10

As stated many times above, using splice() seems like a perfect fit. Documentation at Mozilla:

The splice() method changes the content of an array by removing existing elements and/or adding new elements.

var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];

myFish.splice(2, 0, 'drum'); 
// myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"]

myFish.splice(2, 1); 
// myFish is ["angel", "clown", "mandarin", "sturgeon"]

Syntax

array.splice(start)
array.splice(start, deleteCount)
array.splice(start, deleteCount, item1, item2, ...)

Parameters

start

Index at which to start changing the array. If greater than the length of the array, actual starting index will be set to the length of the array. If negative, will begin that many elements from the end.

deleteCount

An integer indicating the number of old array elements to remove. If deleteCount is 0, no elements are removed. In this case, you should specify at least one new element. If deleteCount is greater than the number of elements left in the array starting at start, then all of the elements through the end of the array will be deleted.

If deleteCount is omitted, deleteCount will be equal to (arr.length - start).

item1, item2, ...

The elements to add to the array, beginning at the start index. If you don't specify any elements, splice() will only remove elements from the array.

Return value

An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.

[...]

serv-inc
  • 29,557
  • 9
  • 128
  • 146
9

It's probably also worth mentioning that splice only works on arrays. (Object properties can't be relied on to follow a consistent order.)

To remove the key-value pair from an object, delete is actually what you want:

delete myObj.propName;     // , or:
delete myObj["propName"];  // Equivalent.
jtrick
  • 1,281
  • 18
  • 20
  • delete doesn't reorder the array keys, so: var arr = [1,2,3,4,5]; delete arr[3]; for (var i = 0; i <= arr.length; i++) console.log(arr[i]); will exhibit unexpected results. – Kristian Williams Nov 14 '16 at 11:42
  • This is true. So unless you want to leave an undefined item at that location, DON'T use delete on an array's keys! I originally added this comment to include a reference of the correct use of delete. – jtrick Dec 05 '16 at 20:24
  • but why delete will throw unexpected result ?? – Alex Sep 19 '18 at 07:36
9

delete Vs splice

when you delete an item from an array

var arr = [1,2,3,4]; delete arr[2]; //result [1, 2, 3:, 4]
console.log(arr)

when you splice

var arr = [1,2,3,4]; arr.splice(1,1); //result [1, 3, 4]
console.log(arr);

in case of delete the element is deleted but the index remains empty

while in case of splice element is deleted and the index of rest elements is reduced accordingly

mitesh7172
  • 546
  • 8
  • 17
Ashish Yadav
  • 2,355
  • 1
  • 11
  • 21
7

delete acts like a non real world situation, it just removes the item, but the array length stays the same:

example from node terminal:

> var arr = ["a","b","c","d"];
> delete arr[2]
true
> arr
[ 'a', 'b', , 'd', 'e' ]

Here is a function to remove an item of an array by index, using slice(), it takes the arr as the first arg, and the index of the member you want to delete as the second argument. As you can see, it actually deletes the member of the array, and will reduce the array length by 1

function(arr,arrIndex){
    return arr.slice(0,arrIndex).concat(arr.slice(arrIndex + 1));
}

What the function above does is take all the members up to the index, and all the members after the index , and concatenates them together, and returns the result.

Here is an example using the function above as a node module, seeing the terminal will be useful:

> var arr = ["a","b","c","d"]
> arr
[ 'a', 'b', 'c', 'd' ]
> arr.length
4 
> var arrayRemoveIndex = require("./lib/array_remove_index");
> var newArray = arrayRemoveIndex(arr,arr.indexOf('c'))
> newArray
[ 'a', 'b', 'd' ] // c ya later
> newArray.length
3

please note that this will not work one array with dupes in it, because indexOf("c") will just get the first occurance, and only splice out and remove the first "c" it finds.

med116
  • 1,384
  • 16
  • 15
6

If you want to iterate a large array and selectively delete elements, it would be expensive to call splice() for every delete because splice() would have to re-index subsequent elements every time. Because arrays are associative in Javascript, it would be more efficient to delete the individual elements then re-index the array afterwards.

You can do it by building a new array. e.g

function reindexArray( array )
{
       var result = [];
        for( var key in array )
                result.push( array[key] );
        return result;
};

But I don't think you can modify the key values in the original array, which would be more efficient - it looks like you might have to create a new array.

Note that you don't need to check for the "undefined" entries as they don't actually exist and the for loop doesn't return them. It's an artifact of the array printing that displays them as undefined. They don't appear to exist in memory.

It would be nice if you could use something like slice() which would be quicker, but it does not re-index. Anyone know of a better way?


Actually, you can probably do it in place as follows which is probably more efficient, performance-wise:

reindexArray : function( array )
{
    var index = 0;                          // The index where the element should be
    for( var key in array )                 // Iterate the array
    {
        if( parseInt( key ) !== index )     // If the element is out of sequence
        {
            array[index] = array[key];      // Move it to the correct, earlier position in the array
            ++index;                        // Update the index
        }
    }

    array.splice( index );  // Remove any remaining elements (These will be duplicates of earlier items)
},
Igor Jerosimić
  • 12,987
  • 6
  • 43
  • 51
Mike T
  • 61
  • 1
  • 1
6

you can use something like this

var my_array = [1,2,3,4,5,6];
delete my_array[4];
console.log(my_array.filter(function(a){return typeof a !== 'undefined';})); // [1,2,3,4,6]
mitesh7172
  • 546
  • 8
  • 17
Zeeshan Saleem
  • 141
  • 2
  • 15
  • this is more intuitive than `slice` if you come from a functional background (probably less efficient, though). – jethro Feb 10 '20 at 21:44
3

Why not just filter? I think it is the most clear way to consider the arrays in js.

myArray = myArray.filter(function(item){
    return item.anProperty != whoShouldBeDeleted
});
Asqan
  • 3,858
  • 10
  • 52
  • 90
  • What about an array with hundreds (if not thousands) of records where only 3 of them need to be removed? – Joel Hernandez Mar 18 '16 at 06:01
  • good point. i use this method for sparse arrays whose length is not more than 200 or 300 and performs very well. However, i think libraries like underline should be preferred if you have to manage such greater arrays. – Asqan Mar 18 '16 at 07:54
  • 1
    However, it seems much nicer than `delete` or `slice` to me. – Juneyoung Oh Oct 15 '18 at 05:27
3

The difference can be seen by logging the length of each array after the delete operator and splice() method are applied. For example:

delete operator

var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
delete trees[3];

console.log(trees); // ["redwood", "bay", "cedar", empty, "maple"]
console.log(trees.length); // 5

The delete operator removes the element from the array, but the "placeholder" of the element still exists. oak has been removed but it still takes space in the array. Because of this, the length of the array remains 5.

splice() method

var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
trees.splice(3,1);

console.log(trees); // ["redwood", "bay", "cedar", "maple"]
console.log(trees.length); // 4

The splice() method completely removes the target value and the "placeholder" as well. oak has been removed as well as the space it used to occupy in the array. The length of the array is now 4.

3

Others have already properly compared delete with splice.

Another interesting comparison is delete versus undefined: a deleted array item uses less memory than one that is just set to undefined;

For example, this code will not finish:

let y = 1;
let ary = [];
console.log("Fatal Error Coming Soon");
while (y < 4294967295)
{
    ary.push(y);
    ary[y] = undefined;
    y += 1;
}
console(ary.length);

It produces this error:

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory.

So, as you can see undefined actually takes up heap memory.

However, if you also delete the ary-item (instead of just setting it to undefined), the code will slowly finish:

let x = 1;
let ary = [];
console.log("This will take a while, but it will eventually finish successfully.");
while (x < 4294967295)
{
    ary.push(x);
    ary[x] = undefined;
    delete ary[x];
    x += 1;
}
console.log(`Success, array-length: ${ary.length}.`);

These are extreme examples, but they make a point about delete that I haven't seen anyone mention anywhere.

Lonnie Best
  • 6,765
  • 9
  • 44
  • 81
2
function remove_array_value(array, value) {
    var index = array.indexOf(value);
    if (index >= 0) {
        array.splice(index, 1);
        reindex_array(array);
    }
}
function reindex_array(array) {
   var result = [];
    for (var key in array) {
        result.push(array[key]);
    }
    return result;
}

example:

var example_arr = ['apple', 'banana', 'lemon'];   // length = 3
remove_array_value(example_arr, 'banana');

banana is deleted and array length = 2

Terry Lin
  • 2,082
  • 16
  • 19
2

They're different things that have different purposes.

splice is array-specific and, when used for deleting, removes entries from the array and moves all the previous entries up to fill the gap. (It can also be used to insert entries, or both at the same time.) splice will change the length of the array (assuming it's not a no-op call: theArray.splice(x, 0)).

delete is not array-specific; it's designed for use on objects: It removes a property (key/value pair) from the object you use it on. It only applies to arrays because standard (e.g., non-typed) arrays in JavaScript aren't really arrays at all*, they're objects with special handling for certain properties, such as those whose names are "array indexes" (which are defined as string names "...whose numeric value i is in the range +0 ≤ i < 2^32-1") and length. When you use delete to remove an array entry, all it does is remove the entry; it doesn't move other entries following it up to fill the gap, and so the array becomes "sparse" (has some entries missing entirely). It has no effect on length.

A couple of the current answers to this question incorrectly state that using delete "sets the entry to undefined". That's not correct. It removes the entry (property) entirely, leaving a gap.

Let's use some code to illustrate the differences:

console.log("Using `splice`:");
var a = ["a", "b", "c", "d", "e"];
console.log(a.length);            // 5
a.splice(0, 1);
console.log(a.length);            // 4
console.log(a[0]);                // "b"

console.log("Using `delete`");
var a = ["a", "b", "c", "d", "e"];
console.log(a.length);            // 5
delete a[0];
console.log(a.length);            // still 5
console.log(a[0]);                // undefined
console.log("0" in a);            // false
console.log(a.hasOwnProperty(0)); // false

console.log("Setting to `undefined`");
var a = ["a", "b", "c", "d", "e"];
console.log(a.length);            // 5
a[0] = undefined;
console.log(a.length);            // still 5
console.log(a[0]);                // undefined
console.log("0" in a);            // true
console.log(a.hasOwnProperty(0)); // true

* (that's a post on my anemic little blog)

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
2

Currently there are two ways to do this

  1. using splice()

    arrayObject.splice(index, 1);

  2. using delete

    delete arrayObject[index];

But I always suggest to use splice for array objects and delete for object attributes because delete does not update array length.

imal hasaranga perera
  • 7,622
  • 2
  • 44
  • 35
1

OK, imagine we have this array below:

const arr = [1, 2, 3, 4, 5];

Let's do delete first:

delete arr[1];

and this is the result:

[1, empty, 3, 4, 5];

empty! and let's get it:

arr[1]; //undefined

So means just the value deleted and it's undefined now, so length is the same, also it will return true...

Let's reset our array and do it with splice this time:

arr.splice(1, 1);

and this is the result this time:

[1, 3, 4, 5];

As you see the array length changed and arr[1] is 3 now...

Also this will return the deleted item in an Array which is [3] in this case...

Alireza
  • 83,698
  • 19
  • 241
  • 152
1

If you have small array you can use filter:

myArray = ['a', 'b', 'c', 'd'];
myArray = myArray.filter(x => x !== 'b');
Emir Mamashov
  • 690
  • 6
  • 11
1

Performance

There are already many nice answer about functional differences - so here I want to focus on performance. Today (2020.06.25) I perform tests for Chrome 83.0, Safari 13.1 and Firefox 77.0 for solutions mention in question and additionally from chosen answers

Conclusions

  • the splice (B) solution is fast for small and big arrays
  • the delete (A) solution is fastest for big and medium fast for small arrays
  • the filter (E) solution is fastest on Chrome and Firefox for small arrays (but slowest on Safari, and slow for big arrays)
  • solution D is quite slow
  • solution C not works for big arrays in Chrome and Safari
    function C(arr, idx) {
      var rest = arr.slice(idx + 1 || arr.length);
      arr.length = idx < 0 ? arr.length + idx : idx;
      arr.push.apply(arr, rest);
      return arr;
    }
    
    
    // Crash test
    
    let arr = [...'abcdefghij'.repeat(100000)]; // 1M elements
    
    try {
     C(arr,1)
    } catch(e) {console.error(e.message)}

enter image description here

Details

I perform following tests for solutions A B C D E (my)

  • for small array (4 elements) - you can run test HERE
  • for big array (1M elements) - you can run test HERE

function A(arr, idx) {
  delete arr[idx];
  return arr;
}

function B(arr, idx) {
  arr.splice(idx,1);
  return arr;
}

function C(arr, idx) {
  var rest = arr.slice(idx + 1 || arr.length);
  arr.length = idx < 0 ? arr.length + idx : idx;
  arr.push.apply(arr, rest);
  return arr;
}

function D(arr,idx){
    return arr.slice(0,idx).concat(arr.slice(idx + 1));
}

function E(arr,idx) {
  return arr.filter((a,i) => i !== idx);
}

myArray = ['a', 'b', 'c', 'd'];

[A,B,C,D,E].map(f => console.log(`${f.name} ${JSON.stringify(f([...myArray],1))}`));
This snippet only presents used solutions

Example results for Chrome

enter image description here

Kamil Kiełczewski
  • 53,729
  • 20
  • 259
  • 241
0

IndexOf accepts also a reference type. Suppose the following scenario:

var arr = [{item: 1}, {item: 2}, {item: 3}];
var found = find(2, 3); //pseudo code: will return [{item: 2}, {item:3}]
var l = found.length;

while(l--) {
   var index = arr.indexOf(found[l])
      arr.splice(index, 1);
   }
   
console.log(arr.length); //1

Differently:

var item2 = findUnique(2); //will return {item: 2}
var l = arr.length;
var found = false;
  while(!found && l--) {
  found = arr[l] === item2;
}

console.log(l, arr[l]);// l is index, arr[l] is the item you look for
mitesh7172
  • 546
  • 8
  • 17
roland
  • 7,135
  • 6
  • 42
  • 60
0

Easiest way is probably

var myArray = ['a', 'b', 'c', 'd'];
delete myArray[1]; // ['a', undefined, 'c', 'd']. Then use lodash compact method to remove false, null, 0, "", undefined and NaN
myArray = _.compact(myArray); ['a', 'c', 'd'];

Hope this helps. Reference: https://lodash.com/docs#compact

serv-inc
  • 29,557
  • 9
  • 128
  • 146
Prashanth
  • 371
  • 1
  • 3
  • 5
  • 1
    Should someone stumble on this wondering about `compact`... no need for lodash. Try `myArray.filter(function(n){return n;})` – dat May 20 '17 at 00:22
0

If the desired element to delete is in the middle (say we want to delete 'c', which its index is 1), you can use:

var arr = ['a','b','c'];
var indexToDelete = 1;
var newArray = arr.slice(0,indexToDelete).combine(arr.slice(indexToDelete+1, arr.length))
mitesh7172
  • 546
  • 8
  • 17
Idan Gozlan
  • 2,631
  • 2
  • 24
  • 43
0

For those who wants to use Lodash can use: myArray = _.without(myArray, itemToRemove)

Or as I use in Angular2

import { without } from 'lodash';
...
myArray = without(myArray, itemToRemove);
...
Ricky Levi
  • 5,482
  • 1
  • 47
  • 55
0

delete: delete will delete the object property, but will not reindex the array or update its length. This makes it appears as if it is undefined:

splice: actually removes the element, reindexes the array, and changes its length.

Delete element from last

arrName.pop();

Delete element from first

arrName.shift();

Delete from middle

arrName.splice(starting index,number of element you wnt to delete);

Ex: arrName.splice(1,1);

Delete one element from last

arrName.splice(-1);

Delete by using array index number

 delete arrName[1];
Srikrushna
  • 2,652
  • 30
  • 37
-1
function deleteFromArray(array, indexToDelete){
  var remain = new Array();
  for(var i in array){
    if(array[i] == indexToDelete){
      continue;
    }
    remain.push(array[i]);
  }
  return remain;
}

myArray = ['a', 'b', 'c', 'd'];
deleteFromArray(myArray , 0);

// result : myArray = ['b', 'c', 'd'];

Eyad Farra
  • 4,338
  • 1
  • 22
  • 26