用推导的另一个数组元素的值创建新数组-JS

时间:2019-02-18 13:21:55

标签: javascript

我需要创建一个数组,该数组具有相同数量的元素,但是应该扣除值。示例:

初始数组:

myArray = [1, 3, 6, 7, 11, 14]

新数组:

newArray = [1, 2, 3, 1, 4, 3]

那么1-0、3-1、6-3等...关于如何实现这一目标的任何建议?

5 个答案:

答案 0 :(得分:4)

const myArray = [1, 3, 6, 7, 11, 14];
const newArray = [];

for(let i = 0;i<myArray.length; i++) {
  if(myArray[i+1] !== undefined) {
  newArray.push(myArray[i+1]-myArray[i]);

  }
}

console.log(newArray)

答案 1 :(得分:2)

myArray = [1, 3, 6, 7, 11, 14];
var i = 0;
console.log(myArray.map(e => {
  var k = e - i;
  i = e;
  return k
}))

答案 2 :(得分:2)

您可以像这样使用.map

let myArray = [1, 3, 6, 7, 11, 14];
let newArray = myArray.map((element, index, myArray) => 
    element - (myArray[index - 1] || 0));
console.log(newArray)

答案 3 :(得分:0)

您可以使用Array.from()

const myArray = [1, 3, 6, 7, 11, 14];

const newArray = Array.from({
  length: myArray.length
}, (_, i) => {
  return myArray[i - 1] ? myArray[i] - myArray[i - 1] : myArray[i]
});

console.log(newArray);

答案 4 :(得分:0)

当您要将2个数组放在一起,或者希望将当前数组或下一个数组或当前/上一个数组合并时,可以使用zip:

const zip = (a, b) =>
  a.map((item, index) => [
    item,
    b[index],
  ]);

const myArray = [1, 3, 6, 7, 11, 14];

console.log(
  zip(myArray, [0].concat(myArray))//[[current,previous],...][[1,0],[3,1],[6,3]...]
  .map(
    ([a, b]) => a - b,
  ),
);