为数组中的每两个元素创建对

ton*_*ony 0 javascript

如何简洁地编写一个函数,使其使用数组中的每一对元素创建一个新的对象数组?

假设元素数为偶数。

示例输入:

input = [1, 42, 55, 20, 3, 21]
Run Code Online (Sandbox Code Playgroud)

输出:

output = [{x:1, y:42}, {x:55, y:20}, {x:3, y:21}]
Run Code Online (Sandbox Code Playgroud)

编辑:这是我不喜欢的当前解决方案:

[1, 42, 55, 20, 3, 21].reduce(
    (acc, curr, i) => (
      i % 2 === 0
        ? [...acc, { x: curr }]
        : [...acc.slice(0, -1), { x: acc[acc.length - 1].x, y: curr }]), []
  )
Run Code Online (Sandbox Code Playgroud)

Mah*_*Ali 6

您可以使用一个for循环,它增加了2

const input = [1, 42, 55, 20, 3, 21];
const res = [];
for(let i = 0; i < input.length; i+=2){
  res.push({x:input[i], y: input[i + 1]});
}
console.log(res)
Run Code Online (Sandbox Code Playgroud)