user1788736
user1788736

Reputation: 2845

How to remove/delete a row in javascript array by having value of first item of array row?

I create array like this:

var myArray = new Array();
myArray.push({ url: urlValue, filename: fileNameValue });

urlValue and fileNamevalue are javascript variables. After a while my array will get lots of items and if i want to delete a row by having urlValue how i can delete that row?(by row i mean delete that urlValue and fileNameValue).For Example i want delete a row that has urlValue= http://www.somsite.com/pics/picture12.jpg and fileNameValue=picseasonNewName.jpg

Upvotes: 2

Views: 87

Answers (4)

Drakes
Drakes

Reputation: 23660

If you use jQuery, you can use grep

var result = $.grep(myArray, function(e){ return e.url !== "urlValue"; });

This will return an array of objects whose url is not the target value, effectively deleting your array entry.

Demo: JSbin

Upvotes: 3

bpbutti
bpbutti

Reputation: 393

The terms you are using in your question are not the right ones for javascript.

What Drakes wrote in the comments expresses better what you want

delete an entry in the array containing the object that has a certain url:urlValue

Javascript has some built-in functions for working with arrays.

You could use filter to make a new array without the entry you wish to remove, and it is also useful if the urlValue is not unique.

function removeEntries(arr, value) {
  return arr.filter(function (entry) {
    return entry.url !== value;
  })
}

Upvotes: 1

Updating an array

  1. Loop an array.
  2. Compare if the item's link is equal to the item you want to delete.
  3. You update the array eliminating what was found

Demo:

var myArray = new Array();
myArray.push({ url: "http://www.somsite.com/pics/picture10.jpg", filename: "" });
myArray.push({ url: "http://www.somsite.com/pics/picture12.jpg", filename: "" });
myArray.push({ url: "http://www.somsite.com/pics/picture14.jpg", filename: "" });

var i = 0, urlToFind = "http://www.somsite.com/pics/picture12.jpg";

//Remove/Delete array item

while(i < myArray.length){
   myArray[i++].url == urlToFind ? myArray.splice(i-1, 1) : 0
}

document.write(JSON.stringify(myArray))

Upvotes: 2

Bill Pope
Bill Pope

Reputation: 591

you can remove the entire object from the array using

function removeRow(value){ 
    for(var i=0; i<myArray.length; i++){
        if(myArray[i].urlValue == value)
           myArray.splice(i,1);
    }
}

Upvotes: 2

Related Questions