Transfer any other value from an array to a new array

I have two one-dimensional arrays, aand b. amatters and is bempty. Length ais an even number. I would like to remove any other value from aand move them bin the same order in which 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 realized that I would filterdo the trick, but I'm not so happy with its performance, as the average length ais 300-400.

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

I also looked at lodash to see if there is anything in this library that could help me, and the only function that is next to what I'm looking for is . _.chunk(array, \[size=1\])

I appreciate any help to help me find the best and fastest way to do this.

+4
4

Vanilla JS ES5, .

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])
  }
}

, a , , b.

+1

. :

const source = [1, 2, 3, 4, 5, 6];

let arrs = [[],[]];
for(let i = 0; i< source.length; i++)
	arrs[i%2].push(source[i]);
let [a,b] = arrs;  
  
console.log(a);
console.log(b);
Hide result

, , a , :

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

for(let i = 0; i< a.length; i++)
	(i % 2 ? b : a)[Math.floor(i/2)] = a[i];
  
a.splice(a.length/2);
  
console.log(a);
console.log(b);
Hide result
+2

lodash, _. 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>
Hide result

- , , i.

, :

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>
Hide result
+2
source

The best performance you can get for this is 0 (n) or linear time, since you need to iterate through the entire array. What can help reduce the number of cycles

var a=[];
var b=[];
function splitArray(arr)
{
    for (var i=0;i<arr.length;++i)
        {
            if (arr[i]%2 == 0)
                b.push(arr[i]);
            else
                a.push(arr[i]); 
        }
}

What this means is that it reduces the number of iteration retries in the original array from 2 to 1

+1
source

Source: https://habr.com/ru/post/1679724/


All Articles