Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

230
Views
javascript Get the difference between an element of an array and the previous one

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?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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)

about 4 years ago · Juan Pablo Isaza Report

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)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!