return FALSE; $r = well_tag_thread__update(array('id' => $id), $update); return $r; } function well_tag_thread_find($tagid, $page, $pagesize) { $arr = well_tag_thread__find(array('tagid' => $tagid), array('id' => -1), $page, $pagesize); return $arr; } function well_tag_thread_find_by_tid($tid, $page, $pagesize) { $arr = well_tag_thread__find(array('tid' => $tid), array(), $page, $pagesize); return $arr; } ?>javascript - Deconstructing an array in increments of two - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Deconstructing an array in increments of two - Stack Overflow

programmeradmin5浏览0评论

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?

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?

Share Improve this question asked Jun 21, 2019 at 18:12 JimmyNeedlesJimmyNeedles 1611 silver badge8 bronze badges 1
  • In a single destructuring statement? No, you'd need an intermediate step. – zero298 Commented Jun 21, 2019 at 18:16
Add a ment  | 

6 Answers 6

Reset to default 7

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);

.flatMap() is a bination of .map() and .flat() it allows the callback to skip returning values, return a value, and return multiple values which is made possible by returning arrays which get flattened in the final step. This demo has a callback which is a ternary that returns 2 values in an array every other iteration while it returns an empty array on alternating iterations. The result is an array of arrays which is then destructured.

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

let newArr = arr.flatMap((node, index, array) => index % 2 !== 0 ? [
  [array[index - 1], node]
] : []);

let [A, B, C] = newArr;

console.log(A);
console.log(B);
console.log(C);

You can do that in following steps:

  • Use reduce() on the array and set accumulator to []
  • During each iteration check the current index is divisible by the given number(2).
  • If it does then add an empty array to the end to accumulator.
  • Add the current element to the last subarray of accumulator each time.

let arr = [1, 2, 3, 4, 5, 6, "a"];
let [first,second,third] = arr.reduce((ac,a,i) => {
  if(i % 2 === 0){
     ac.push([]);
  } 
  ac[ac.length - 1].push(a);
   return ac;
},[])

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

Here is another curried version using a Generator, but this one uses Array.splice() to yield the values:

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

const getChunk = (len) => function * (arr)
{
    arr = arr.slice(0);

    while (arr.length >= len)
        yield arr.splice(0, len);

    yield arr;
}

let [one, two, three, four] = getChunk(2)(arr);
console.log("Chunks of size 2 =>", JSON.stringify([one, two, three, four]));

[one, two, three, four] = getChunk(3)(arr);
console.log("Chunks of size 3 =>", JSON.stringify([one, two, three, four]));

[one, two, three, four] = getChunk(1)(arr);
console.log("Chunks of size 1 =>", JSON.stringify([one, two, three, four]));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

is that possible?

Most anything is possible with coding.

let group = (arr, count) => 
  arr.reduce((acc, v) => {
    let last = acc[acc.length - 1];
    if (last.length < count)
      last.push(v);
    else
      acc.push([v]);
    return acc;
  }, [[]]);

let arr = [1, 2, 3, 4, 5, 6, "a"]
console.log(group(arr, 2));
console.log(group(arr, 3));
console.log(group(arr, 5));

发布评论

评论列表(0)

  1. 暂无评论