Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment numbers in mapped array using Ramda

I have an array that looks like this:

[{location: {…}, distance: 0}
{location: {…}, distance: 0}
{location: {…}, distance: 0.37348441209694133}
{location: {…}, distance: 0}
{location: {…}, distance: 0.4229382782128456}
{location: {…}, distance: 0}
{location: {…}, distance: 0.006098292961396555}
{location: {…}, distance: 0}
{location: {…}, distance: 0.07885846317546494}]

I want to map a new array with the distance values incremented from the previous value. So in the example above the last distance value would be 0.88137944644665 because it was have added all the values by the time it iterated all objects.

In Ramda.js I've tried to add the previous distance value when I map the array but it doesn't work because it's undefined. I've also looked into reduce with no success. Any ideas on how I can accomplish this in Ramda.js?

like image 338
londonfed Avatar asked Jan 21 '26 15:01

londonfed


1 Answers

Much as I love Ramda you don't need it here:

arr.map(({ location, distance }) => ({ location, distance: distance + 1 }));

To break that down:

arr // your array of objects
  .map( // call to Array.prototype.map
    ({ location, distance }, i, arr) => // function params, destructures
      ({ location, distance: distance + 1 })); // return new object same loc, incremented distance

EDIT

Since I missed the part about aggregation, use reduce instead:

arr.reduce((aggregate, { location, distance }, i) => {
  const dist = i ? aggregate[i - 1].distance : 0;
  aggregate.push({ location, distance: distance + dist });
  return aggregate;
}, []);  
like image 77
Jared Smith Avatar answered Jan 23 '26 04:01

Jared Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!