使用javascript数组减少给定n个输入以产生m个输出

我有一系列要点,我想改成一系列的.

这是我想要的代码的一个例子

[p1, p2, p3] -> [line1, line2]

每个循环:

(p1, p2) -> line
(p2, p3) -> line

执行此操作的标准方法是:

const triangle = [[0,0], [0,1], [1,2]]

const lines = []
for (let i = 1; i < triangle.length; ++i) {
  const slope = findSlopeFromPoints(...triangle[i - 1], ...triangle[i])
  const yIntercept = findYIntercept(...triangle[i], slope)
  lines.push({
    slope,
    yIntercept
  })
}

这是我可以使用Array.prototype.reduce获得的关闭.但感觉更难理解

const initial = {
  array: [], // actual returned array we care about
  lastPoint: null // "triangle[i - 1]"
}
const linesR = triangle.reduce( (lines, point) => {
  if (lines.lastPoint === null)
    return { 
      ...lines, 
      lastPoint: point 
    }
  else {
    const slope = findSlopeFromPoints(...lines.lastPoint, ...point)
    const yIntercept = findYIntercept(...point, slope)
    lines.array.push({
      slope,
      yIntercept
    })
    lines.lastPoint = point
    return lines

  }
}, initial )

简而言之,有没有更好的方法来使用reduce将N个输入组合成N-1个输出?

最佳答案 当然,使用currentIndex参数来应用偏移量.您的回调函数会收到比您正在使用的更多的参数1:

[{x:0, y:0}, {x:0, y:1}, {x:1, y:2}].reduce((lines, point, currentIndex, source) => {
  currentIndex < source.length -1 && lines.push({
    from: point,
    to: source[currentIndex + 1]
  }); 
  return lines;     
}, []);

1有关详细信息,请参见Array.prototype.reduce().

点赞