0

How can you find a section of a JS array and delete it? What I mean is a function that can find a string, looks at an array, sees if one of the "sections" are exactly like the string, and deletes that "section". Here's what I have:

var array = ['a1','f4'];
function findAndDelete(string){
    delete array.find('a1');
}

When I try it, nothing happens. It seems that there's a syntax error. How do I fix this?

5 Answers5

2
var array = ['a1','f4'];
function findAndDelete(string){
    var index = array.indexOf(string);
    if (index > -1) {
      array.splice(index, 1);
    }
}

Here we can use splice() method of array to delete specific element from it.

  • splice deletes an item located at the index from the array, and deletes the next items in the array as well up to the number, so 1 in the last argument deletes 1 item, 2 deletes the found item and the next one. It also returns the deleted items, so you could do `var deletedArray = array.splice(index, 1);` – TRGWII Feb 18 '15 at 04:38
0

This should work

var array = ['a1','f4'];
var index = array.indexOf('a1');

if (index > -1) {
   array.splice(index, 1);
}

splice will actually return a new array containing elements which were removed.

Sergey Akopov
  • 1,080
  • 10
  • 24
0

Use this:

function findAndDelete(array, string){
  if(array.indexOf(string) !== -1) array.splice(array.indexOf(string), 1);
}

var array = ['a1', 'f4'];
findAndDelete(array, 'a1');

JSON.stringify(array); // ['f4'];

a couple of things are happening here:

array.indexOf finds the numeric index of the value (in this case 0 is the index because array[0] == 'a1') (If the value is not found the index returned will be -1)

array.splice uses the index to delete the item located at that index, the second numer specifies how many elements to delete from there.

TRGWII
  • 638
  • 6
  • 14
0

There are two possible solutions to this problem, depending on what you want to get out of the function. The first solution will work well if there is only ever one element in the array that matches the string, of it you only want to delete the first element that matches. The second solution will delete all instances of the string passed into the function.

Delete the First Element to Match the String Passed In

The solution that I found to delete one element that matches your passed in string is to use the array.indexOf() method, test the value from that method and, if the index returns a value other than -1, then to pass the index to splice and delete the element from the array. My code is as follows:

var array = ['a1','f4'];

function findAndDelete(arg){

    var testString = arg;
    var index = array.indexOf(testString); //cache index 

    if(index !== -1){
        array.splice(index,1);
    }
}//end findAndDelete()

Once a string is passed into the function, it is stored in the testString variable. Then, we call array.indexOf(testString) and cache the value returned by the function in the index variable. This value is cached to optimize the script and to keep the code DRY (Don't Repeat Yourself). The value of index is then tested to see if it is anything other than -1. The reason index is tested against -1 is because, if the string passed into indexOf() does not exist, the function will return -1. So, if index is not -1, we know that the string passed in exists in the array. The index of that value is then passed to splice as the first argument, which tells where to begin the splice in the array. The second argument passed into splice is the number of element to delete from the array. Since we are only deleting one element of the array, we always pass 1.

You could also create a function that loops through the array with a for-loop and checks every element against the testString. This will work just as well, but is going to be a less efficient way of solving your problem if there will only ever be one element in the array that could match the string you are passing into the function.

Deleting All Instances of the String Passed In

However, the solution I listed above will not work if there are two identical string in the array. For example, if array=['a1','f4','a1'], the function will only delete the first element that it finds. So, after running the function with an argument of 'a1' the array will be: array=['f4','a1']. If you want to be able to delete all elements of an array that match the string you have input, the for-loop solution will work best. The following code would work if you want to delete all elements of an array that match your input:

var array = ['a1','f4', 'a1'];

function findAndDelete(arg){

    var testString = arg;

    for(var i = 0; i< array.length; i++){
        if(testString === array[i]){
            array.splice(i,1);
        }

    }//end for-loop

}//end findAndDelete()

Additionally, if the script is running on IE 8 or older, the indexOf() method will not work. You will need to use the for-loop solution or look for another way to solve your problem.

Community
  • 1
  • 1
MKreegs
  • 138
  • 1
  • 8
  • In the "deleting all instances" example, if duplicates are adjacent, it will skip every second one as *splice* shifts the indexes of subsequent members and the loop doesn't account for it. To avoid that issue, iterate from the end to the start (otherwise decrement *i* each time *splice* is called). – RobG Sep 03 '15 at 07:27
-1

You are using find() incorrectly. The function you want is indexOf().

IndexOf() returns the index of the value you give it. So you just need to replace

delete array.find('a1');

with

delete array[array.indexOf('a1')];

Note that this only removes the first instance of it.

James Westman
  • 2,468
  • 1
  • 14
  • 19
  • `delete` when used on an array element does not change the length of the array or move the other elements down in the array. Probably not what one wants if they are using an array. – jfriend00 Feb 18 '15 at 04:28
  • @jfriend00 Thanks, I was not aware of that. – James Westman Feb 18 '15 at 04:30