Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

the latter element subtract the previous element in javascript

There is an array:

let arr=[
    [1000,800,1,"true"],
    [1500,0,2,"false"],
    [1600,0,3,"true"],
    [2500,300,4,"false"]
]

I want the result:

let arr_result=[
    [1000,800,1,"true"],
    [500,0,2,"false"],
    [100,0,3,"true"],
    [900,300,4,"false"]
]

That is, let the latter sub-array element[0] subtract the previous sub-array element[0].
I need to do it in javascript.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How to do it?

>Solution :

You can use map method and then simply use index param to get previous element by using array[index - 1] and then first element of that sub array.

let arr = [
  [1000, 800, 1, "true"],
  [1500, 0, 2, "false"],
  [1600, 0, 3, "true"],
  [2500, 300, 4, "false"]
]

const result = arr.map(([e, ...rest], i) => (
  [i ? e - arr[i - 1][0] : e, ...rest]
))

console.log(result)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading