Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

232
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda