Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
491 views
in Technique[技术] by (71.8m points)

arrays - How to subtract next object to the previous one and again subtract the value i got with other next value and so on in Javascript?

(14) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {date: "2019-11-28", views: "34731", clicks: "208", likes: "3834"}
1: {date: "2018-09-29", views: "69811", clicks: "361", likes: "5935"}
2: {date: "2017-12-30", views: "80107", clicks: "412", likes: "6526"}
3: {date: "2016-10-31", views: "88390", clicks: "445", likes: "6989"}

This is the array I have, I want to subtract object[0] with the object[1], and then with the value I got I want to print it and again, I want to subtract that value which I got previously with object[2] and get the value, print it and again subtract it with the object[3] and so on till the end and print the value in a table.

I want the end result of the array as given below

0: {date: "2019-11-28", views: "34731", clicks: "208", likes: "3834"}
1: {date: "2018-09-29", views: "35080", clicks: "153", likes: "2101"}
2: {date: "2017-12-30", views: "45027", clicks: "259", likes: "4425"}
3: {date: "2016-10-31", views: "43363", clicks: "186", likes: "2564"}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is a version using reduce

NOTE: if you do not clone the original items, the code ALSO modifies the original which might not be what you want and is sort of ruining the reason for using reduce (forEach would then be better)

Here I clone via spread - thanks TJ for teaching me a lesson here

const original = [
    {date: "2019-11-28", views: "34731", clicks: "208", likes: "3834"},
    {date: "2018-09-29", views: "69811", clicks: "361", likes: "5935"},
    {date: "2017-12-30", views: "80107", clicks: "412", likes: "6526"},
    {date: "2016-10-31", views: "88390", clicks: "445", likes: "6989"},
];

const result = original.reduce((acc, _, i) => { // we do not use the current item
  const item = {...original[i]} // IMPORTANT property spread copy or you will modify the original

  if (i > 0) {
    const prev   = acc.length - 1;
    item.views  -= acc[prev].views;
    item.clicks -= acc[prev].clicks;
    item.likes  -= acc[prev].likes;
  }
  acc.push(item)
  return acc
}, [])
console.log(result);

console.log(original);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...