简体   繁体   中英

How do I obtain the array

I have an array of objects. Each object has an key of leftpixel. What I am trying to achieve is to obtain an array ie newArray with elements that are derived by subtracting leftpixel key value of first obj in array with second leftpixel key value that would make first element of newArray, second element would be obtained by subtracting leftpixel key value of second obj in array with third leftpixel key value.

The array that I have is like this

[
  { 
    A: "FSDF"
    B: "$145.0"
    leftpixel: 2 
  },
  { 
    A: "DFH"
    B: "$463.0"
    leftpixel: 191 
  },
  { 
    A: "FDH"
    B: "$546.0"
    leftpixel: 191 
  },
  { 
    A: "DSG"
    B: "$154.0"
    leftpixel: 192
  }
]

The new Array that I want should be like this

newArray = [189, 0, 1] 

You could slice the array and get the delta of the sliced array items and the original array at the same index,

 var data = [{ A: "FSDF", B: "$145.0", leftpixel: 2 }, { A: "DFH", B: "$463.0", leftpixel: 191 }, { A: "FDH", B: "$546.0", leftpixel: 191 }, { A: "DSG", B: "$154.0", leftpixel: 192 }], deltas = data.slice(1).map((v, i) => v.leftpixel - data[i].leftpixel); console.log(deltas);

This is a slightly verbose implementation that also includes the first value which can be sliced/filtered out later.

 let data = [{ A: "FSDF", B: "$145.0", leftpixel: 2 }, { A: "DFH", B: "$463.0", leftpixel: 191 }, { A: "FDH", B: "$546.0", leftpixel: 191 }, { A: "DSG", B: "$154.0", leftpixel: 192 } ] let result = data.map((item, index, arr) => { if (index === 0) { return item.leftpixel; } return item.leftpixel - arr[index - 1].leftpixel }) console.log(result.slice(1))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM