'Javascript filter based upon previous value

I am trying to rewrite a function in ES6 to use filtering over an array of objects. Currently the code loops through the array and copies array members that meet a criteria to a new array which it then returns. The criteria is based upon the previous value in the array. I want to filter out all array items where the timestamp field of the object is < 4 minutes.

let final = [];
final.push(data[0]);

for (let i = 1, j = data.length; i < j; i++) {
    // if time difference is > 4 minutes add to our final array
    if (data[i].timestamp - data[i-1].timestamp > 240) {
        final.push(data[i]);
    }
}
return final;

There has got to be a better way of doing this. I thought of using an arrow function, but I dont see how I would access the timestamp of the previous array item object when iterating.



Solution 1:[1]

let prevTs = -Infinity;
const result = data.filter((d) => {
  const localResult = (d.timestamp - prevTs) > 240;
  prevTs = d.timestamp;
  return localResult;
});

Or you can use index arg in your filter callback:

data.filter((d, i) => {
  if (!i) {
    return true;
  }
  return (d.timestamp - data[i - 1].timestamp) > 240
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Eugene Tsakh