Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deconstructing an array in increments of two

Say I have an array like so:

let arr = [1, 2, 3, 4, 5, 6, "a"]

How can I deconstruct it in into individual variables in increments of two? So that let one = [1, 2], let two = [3, 4], etc? I know that you can deconstruct an array using individual variables like so:

let one, two, three;
[one, two, three] = arr

But doing it in increments of two, is that possible?

like image 670
JimmyNeedles Avatar asked Jun 21 '19 18:06

JimmyNeedles


Video Answer


2 Answers

Another way you could do this is via ES6 generator function:

let arr = [1, 2, 3, 4, 5, 6, 'a']

function* batch (arr, n=2) {
  let index = 0
  while (index < arr.length) {
    yield arr.slice(index, index + n)
    index += n
  }
}

let [first, second, third] = batch(arr)

console.log(first)
console.log(second)
console.log(third)

Or even more generic approach as kindly suggested by @Patrick Roberts:

let arr = [1, 2, 3, 4, 5, 6, 'a']

function* batch (iterable, length=2) {
  let array = [];
  for (const value of iterable) {
    if (array.push(value) === length) {
      yield array;
      array = [];
    }
  }
  if (array.length) yield array;
}

let [first, second, third] = batch(arr);

console.log(first)
console.log(second)
console.log(third)

And finally a curried version:

let arr = [1, 2, 3, 4, 5, 6, 'a']

const batch = length => function* (iterable) {
  let array = [];
  for (const value of iterable) {
    if (array.push(value) === length) {
      yield array;
      array = [];
    }
  }
  if (array.length) yield array;
}

let [first, second, third] = batch(2)(arr);

console.log(first)
console.log(second)
console.log(third)
like image 109
Akrion Avatar answered Sep 28 '22 21:09

Akrion


You could take an array and assign the value to the explicit target.

An automatic assignment is on the left hand side not possible by using a spread syntax with arrays with a length of two.

let array = [1, 2, 3, 4, 5, 6, "a"],
    one = [], two = [], three = [];

[one[0], one[1], two[0], two[1], three[0], three[1]] = array;

console.log(one);
console.log(two);
console.log(three);
like image 30
Nina Scholz Avatar answered Sep 28 '22 20:09

Nina Scholz