Home > Blockchain >  javascript Get the difference between an element of an array and the previous one
javascript Get the difference between an element of an array and the previous one

Time:09-27

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?

CodePudding user response:

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);

CodePudding user response:

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)

CodePudding user response:

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)

CodePudding user response:

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)
  • Related