Iterate an array as a pair (current, next) in JavaScript

前端 未结 13 923
情话喂你
情话喂你 2020-12-09 09:06

In the question Iterate a list as pair (current, next) in Python, the OP is interested in iterating a Python list as a series of current, next pairs. I have th

相关标签:
13条回答
  • 2020-12-09 10:08

    Here's a simple one-liner:

    [1,2,3,4].reduce((acc, v, i, a) => { if (i < a.length - 1) { acc.push([a[i], a[i+1]]) } return acc; }, []).forEach(pair => console.log(pair[0], pair[1]))
    

    Or formatted:

    [1, 2, 3, 4].
    reduce((acc, v, i, a) => {
      if (i < a.length - 1) {
        acc.push([a[i], a[i + 1]]);
      }
      return acc;
    }, []).
    forEach(pair => console.log(pair[0], pair[1]));
    

    which logs:

    1 2
    2 3
    3 4
    
    0 讨论(0)
提交回复
热议问题