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?
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)
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With