So I have an array of 2-element arrays, and I'm wondering if any of you know how to remove an array given the two elements of an array.
For example, the array would contain the following elements:
[1, 3]
[2, 5]
[1, 1]
Given the two numbers 2 and 5 in that order, is there any way to remove the second array?
-
You want to remove any/all arrays containing exactly those 2 numbers in any order?Sébastien– Sébastien2013年10月22日 00:02:54 +00:00Commented Oct 22, 2013 at 0:02
-
I tried creating a new array and then using indexOf before realizing that indexOf didn't work that way. I've also considered iterating through with a for loop, checking each array at each index for a match and storing it if it is, and then removing it at the end, but I was wondering if there was a more efficient method.user2884505– user28845052013年10月22日 00:36:01 +00:00Commented Oct 22, 2013 at 0:36
2 Answers 2
Search the array for a match by some method. You could try each comparing each list in the larger list to the list given to you, or create a list from the numbers given to you and pass that. Then compare item by item for each list until you match each item-for-item every one.
If you find it use that index and look into the splice method from the javascript library. For example my_lisy.splice(2,2) argument 1 refers to the index of the list, and argument two refers how many items to remove.
Comments
You can try something like this:
var arr = [[1, 3], [2, 5], [1, 1]];
var result = [];
for(var i = 0, len = arr.length; i < len; i++) {
// If the element is the one we don't wan't, skip it
if(arr[i][0] == 2 && arr[i][1] == 5) {
continue;
}
// Otherwise, add it to the result
result.push(arr[i]);
}
console.log(result); //[[1, 3], [1, 1]]
You can add or extract any logic from the loop to suit your needs
1 Comment
Explore related questions
See similar questions with these tags.