Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move every other value from array into a new array

I have two one-dimensional arrays, a and b. a has values and b is empty. The length of a is an even number. I'd like to remove every other value from a and move them to b, in the same order as they were placed in a.

var a = [1, 2, 3, 4, 5, 6], b = [];

becomes

var a = [1, 3, 5], b = [2, 4, 6];

I figured that filter would do the trick but I'm not that happy with the performance of it since the average length of a is 300-400.

b = a.filter((i, idx) => {
    return idx % 2 == 0;
});
a = a.filter((i, idx) => {
    return idx % 2 == 1;
});

I've also been looking at lodash to see if that library had anything that might help me and the only function that's near what I'm looking for is _.chunk(array, \[size=1\]).

I appreciate any and all help to help me figure out a better, faster way to do this.

like image 746
Magnus Avatar asked Jun 20 '17 14:06

Magnus


People also ask

How do I move an element from one array to another?

Create a temp variable and assign the value of the original position to it. Now, assign the value in the new position to original position. Finally, assign the value in the temp to the new position.

How do I copy an element from one array to another in JavaScript?

“concat()” is another useful JavaScript method that can assist you in copying array elements. In the concat() method, you can take an empty array and copy the original array elements to it. It will create a fresh copy of the specified array. var array2 = [].

How do you shift an array in JavaScript?

JavaScript Array shift() The shift() method removes the first item of an array. The shift() method changes the original array.


2 Answers

Since you mentioned lodash you could do this with _.partition:

let a = [1, 2, 3, 4, 5, 6];
let b = [];
let i = -1;

[a, b] = _.partition(a, (item) => i++ % 2);

console.log(a);
console.log(b);
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>

Partition's predicate is the identity function, which doesn't include the index of the item, so this comes with a compromise of an external index i.

Of course, you could always wrap this functionality into it's own function:

const splitEvenOdd = (array, i = -1) => _.partition(array, (item) => i++ % 2);

let a = [1, 2, 3, 4, 5, 6];
let b = [];

[a, b] = splitEvenOdd(a);

console.log(a);
console.log(b);
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>
like image 106
chazsolo Avatar answered Oct 13 '22 01:10

chazsolo


Vanilla JS ES5, simple and clean.

var a = [1, 2, 3, 4, 5, 6], b = [];

for(var i = a.length-1; i >= 0; i--) {
  if(i % 2 === 1) {
    b.unshift(a.splice(i, 1)[0])
  }
}

Basically, it is iterating through a backwards, and if the condition is true splicing the item und adding it as first item of b.

like image 40
Hinrich Avatar answered Oct 13 '22 02:10

Hinrich