Jeff Voss
Jeff Voss

Reputation: 3695

Splice multiple arrays iteratively

What is the fastest way to iteratively splice multiple arrays as you go along - without too much performance hit? I imagine it being something like the syntax below but it doesn't quite work.

I'd like to do: Array1 - remove[0], Array2 - remove[1], Array3 - remove[2]... and so on...

for (var i = 0; i < items.length; i++) {
    arr[i] = items.name;
    for(key in arr[i]) {
        var value = arr[i].splice(i, 1);
        console.log(value);
    }
}

enter image description here

EDIT (definition of items):

enter image description here

Desired Result (3 arrays with 1st, 2nd, 3rd items removed, respectively:

[array0]
  [0] United Kingdom
  [1] United States

[array1]
  [0] Canada 
  [1] United States

[array2]
  [0] Canada
  [1] United Kingdom

EDIT2 - if you look at the following comparison, you can see if we use a for loop to push the incoming arrays into group, the result is identical to the solution provided by Corey, but if we run the splice methods on both of those - the results are very different, example 2 is getting spliced correctly - example 1 is getting spliced entirely, that is where I am confused :

(items are coming in the form of:)

["Canada", "United Kingdom", "United States"] 
["Canada", "United Kingdom", "United States"] 
["Canada", "United Kingdom", "United States"] 


var group = [];

for (var i = 0; i < items.length; i++) {
    group.push(items.name);
}

/*for (var i = 0; i < group.length; i++) {
   group[i].splice(i, 1);
}*/

console.log(group);

var arr1 = ["One", "Two", "Three"];
var arr2 = ["One", "Two", "Three"];
var arr3 = ["One", "Two", "Three"];

var test = [arr1, arr2, arr3];

/*for (var i = 0; i < test.length; i++) {
   test[i].splice(i, 1);
}*/

console.log(test);      

Upvotes: 1

Views: 1421

Answers (2)

Corey
Corey

Reputation: 5818

If all of your Arrays are in another "grouped" Array you could just iterate through the group and use the index as your splice counter. Something like:

var arr1 = ["One", "Two", "Three"];
var arr2 = ["One", "Two", "Three"];
var arr3 = ["One", "Two", "Three"];

var group = [arr1, arr2, arr3];

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

console.log(group);
// Logs: ["Two", "Three"], ["One", "Three"], ["One", "Two"]

Upvotes: 1

Paul
Paul

Reputation: 36319

If you don't mind using a third party library, the easiest way is to use Underscore.js. I'm not clear on whether you want to selectively splice, or if you're just trying to create one array that's a union of the others, or with unique values, or what. But they have operations for all those things:

http://underscorejs.org/#union

If you dont' want to bring them in, then just look at hte source and see how they do it.

Upvotes: 0

Related Questions