Reputation: 139
I have been trying to delete specific parts of an array, and I thought I had it working. But I cannot figure out why I cannot delete the first record.
If I set arrayToDelete to 67(representing the first element of 2nd array), or 9(representing the first element of 3rd array)...it works as I expected. But if I change arrayToDelete to 7(representing the first element of 1st array), it doesn't remove that one.
Where am I going wrong?
var mainArray = [];
var a = [7,"red","Q","gtgtg"];
mainArray.push(a);
var b = [67,"blue","s","ghft"];
mainArray.push(b);
var c = [9,"green","t","rtryt"];
mainArray.push(c);
var pickle = JSON.stringify(mainArray);
console.log("starting array - "+pickle);
console.log("starting array length - "+mainArray.length);
var arrayToDelete = "67";
var getLoc = "";
// Get position of array where first value is "1"
for (var i = 0; i < mainArray.length; i++) {
//console.log(mainArray[i][0]);
if(mainArray[i][0] == arrayToDelete){
//console.log("array number "+i);
getLoc = i;
}
}
console.log("that number was spotted in position - "+getLoc);
//Delete from
if(getLoc != "" && getLoc != "-1"){
mainArray.splice(getLoc, 1);
}
var pickle2 = JSON.stringify(mainArray);
console.log("Array after removal - "+pickle2);
console.log("ending array length - "+mainArray.length);
Upvotes: 1
Views: 104
Reputation: 746
Your error is in getLoc != ""
. This is false
for getLoc === 0
.
I know js is not a strong-typed language, but you'll be better of if you write with strong-typed equality checks ===
See e.g. this article for more insights on the subject http://www.sitepoint.com/borrowing-techniques-strongly-typed-languages-javascript/ and it's always a good choice to run your code through a static code analyzer (e.g. http://jslint.com or http://jshint.com).
Upvotes: 5
Reputation: 633
Functional approach might be much more readable in this case:
mainArray = mainArray.filter(arr => arr[0] !== arrayToDelete);
Upvotes: 1
Reputation: 1254
Add console.log(getLoc != "")
before //Delete from
, and you will see printed false when getLoc=0.
Change
console.log("that number was spotted in position - "+getLoc);
//console.log(getLoc != "")
//Delete from
if(getLoc != "" && getLoc != "-1"){
mainArray.splice(getLoc, 1);
}
by
console.log("that number was spotted in position - "+getLoc);
//console.log(getLoc !== "")
//Delete from
if(getLoc !== "" && getLoc != "-1"){
mainArray.splice(getLoc, 1);
}
Upvotes: 2