-1

Assuming I have an array of milliseconds values like this:

   const array = [
     1633236300000,
     1633244100000,
     1633248000000,
     1633252500000,
     1633287600000,
     1633291500000
   ]

How can I get the difference between an element of an array and the previous one?

ufollettu
  • 822
  • 3
  • 19
  • 45
  • What have you tried so far? What should the output be? – Dominik Sep 26 '21 at 22:23
  • Does this answer your question? [JavaScript go through array and subtract each item with next](https://stackoverflow.com/questions/53260142/javascript-go-through-array-and-subtract-each-item-with-next) – pilchard Sep 26 '21 at 22:37

4 Answers4

2

1) You can use old-style for loop with the starting index as 1

const array = [
  1633236300000, 1633244100000, 1633248000000, 1633252500000, 1633287600000,
  1633291500000,
];

const result = [];
for (let i = 1; i < array.length; ++i) {
  result.push(array[i] - array[i - 1]);
}

console.log(result);

2) You can also use map with slice

const array = [
  1633236300000, 1633244100000, 1633248000000, 1633252500000, 1633287600000,
  1633291500000,
];

const result = array.map((n, i, src) => n - (src[i - 1] ?? 0)).slice(1);

console.log(result);

3) You can also use reduce here

const array = [
  1633236300000, 1633244100000, 1633248000000, 1633252500000, 1633287600000,
  1633291500000,
];

const result = array.reduce((acc, curr, i, src) => {
  if (i !== 0) acc.push(curr - src[i - 1]);
  return acc;
}, []);

console.log(result);
DecPK
  • 24,537
  • 6
  • 26
  • 42
1

Create a new array by slicing from the 2nd element (index 1) to the end, and map it. Take an item from the original array, using the index (i), and substract it from the current item (t).

const array = [1633236300000,1633244100000,1633248000000,1633252500000,1633287600000,1633291500000]

const diff = array.slice(1)
  .map((t, i) => t - array[i])
  
console.log(diff)
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

Get the index of the item in the array, then subtract the item at the previous index from the current one:

const array = [
  1633236300000,
  1633244100000,
  1633248000000,
  1633252500000,
  1633287600000,
  1633291500000
]


const num = 1633291500000;

const diff = num - array[array.indexOf(num) - 1];

console.log(diff)
Spectric
  • 30,714
  • 6
  • 20
  • 43
0

Something like this:

function getDiff (n) {
  if (array.indexOf(n) === 0) return 'no previous time'
  return n - array[array.indexOf(n) - 1]
}

const d = getDiff(array[0])
console.log(d)
t56k
  • 6,769
  • 9
  • 52
  • 115