Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splicing a string indexed array in JavaScript

I have a string indexed array that I would like to remove an item from.

Consider the following example code:

    var arr = new Array();       
    arr[0] = "Zero";
    arr[1] = "One";
    arr[2] = "Two";
    arr.splice(1, 1);

    for (var index in arr)
        document.writeln(arr[index] + " ");

    //This will write: Zero Two

    var arr = new Array();
    arr["Zero"] = "Zero";
    arr["One"] = "One";
    arr["Two"] = "Two";

    arr.splice("One", 1); //This does not work
    arr.splice(1, 1); //Neither does this

    for (var index in arr)
        document.writeln(arr[index] + " ");

    //This will write: Zero One Two

How do I remove "One" from the second example like I did in the first?

like image 906
Michael Avatar asked Jun 04 '09 06:06

Michael


People also ask

Can you splice strings JavaScript?

Javascript splice is an array manipulation tool that can add and remove multiple items from an array. It works on the original array rather than create a copy. It 'mutates' the array. It doesn't work with strings but you can write your own functions to do that quite easily.

How JavaScript splice works in array?

The splice() method is a built-in method for JavaScript Array objects. It lets you change the content of your array by removing or replacing existing elements with new ones. This method modifies the original array and returns the removed elements as a new array.

Can you index an array with string?

Javascript arrays cannot have "string indexes". A Javascript Array is exclusively numerically indexed. When you set a "string index", you're setting a property of the object.


2 Answers

The proper way to do this is not with an Array but an object:

var x = {};
x['Zero'] = 'Zero';
x['One'] = 'One';
x['Two'] = 'Two';
console.log(x); //  Object Zero=Zero One=One Two=Two
delete x['One'];
console.log(x); //  Object Zero=Zero Two=Two
like image 190
Paolo Bergantino Avatar answered Sep 20 '22 16:09

Paolo Bergantino


Once an Array has string keys (or numbers that don't follow), it becomes an Object.

An object doesn't have the splice method (or not the same as Array). You have to write your own, by making a new object and copy into it the key you want to keep.

But be careful ! The keys are not always ordered in the same way they were added in the object ! It depends on the browser.

like image 23
Fabien Ménager Avatar answered Sep 19 '22 16:09

Fabien Ménager