Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert array to array of objects with reduce

Tags:

optimizedRoute = ['Bengaluru', 'Salem', 'Erode', 'Tiruppur', 'Coimbatore']  result = [   {start: bengaluru, end: salem},   {start: salem, end: erode},   {start: erode, end: tiruppur},   {start: tiruppur, end: coimbatore}, ] 

I want to convert optimizedRoute to result. I want to do this with ES6 .reduce(). Here is what I've tried:

const r = optimizedRoute.reduce((places, place, i) => {   const result: any = [];   places = []   places.push({     startPlace: place,     endPlace: place   });   // result.push ({ startplace, endplace, seats: 4 });   // console.log(result);   return places; }, {}); console.log(r) 
like image 935
kartik Avatar asked Jul 18 '18 08:07

kartik


People also ask

How do you reduce an array of arrays?

Using the reduce method. The reduce() method executes a reducer function (a function that you provide as an argument) on each element of the array, resulting in a single output value. Here, the reducer function provided is concat() and the result is stored in an empty array.

Can you use reduce on objects?

reduce can use initial and return values of any type, which makes it very flexible. Let's explore how we can use it to perform some common tasks with plain objects.

Can array reduce return another array?

The array reduce in JavaScript is a predefined method used to reduce an array to a single value by passing a callback function on each element of the array. It accepts a function executed on all the items of the specified array in the left-to-right sequence. The returned single value is stored in the accumulator.

How do you transform an array of objects?

To convert an array of objects to a Map , call the map() method on the array and on each iteration return an array containing the key and value. Then pass the array of key-value pairs to the Map() constructor to create the Map object.


1 Answers

You could use reduce for getting start and end part of the route and return the end for the next start.

getParts = a => (                   // take a as array and return an IIFE     r => (                          // with an initialized result array         a.reduce((start, end) => (  // reduce array by taking two values             r.push({ start, end }), // push short hand properties             end                     // and take the last value as start value for next loop         )),         r                           // finally return result     ) )([]);                              // call IIFE with empty array 

const getParts = a => (r => (a.reduce((start, end) => (r.push({ start, end }), end)), r))([]);    var optimizedRoute = ['Bengaluru', 'Salem', 'Erode', 'Tiruppur', 'Coimbatore']    console.log(getParts(optimizedRoute));
.as-console-wrapper { max-height: 100% !important; top: 0; }

@EDIT Grégory NEUT adding explaination

// Two thing to know first :    // When no initial value is provided,  // Array.reduce takes the index 0 as first value and start to loop at index 1    // Doing (x, y, z)  // Will execute the code x, y and z    // Equivalent to :    // x;  // y;  // z;    let ex = 0;    console.log((ex = 2, ex = 5, ex = 3));    // So about the code    const getParts = (a) => {    // We are creating a new function here so we can have an array where to    // push data to    const func = (r) => {      // Because there is no initial value      //      // Start will be the value at index 0 of the array      // The loop is gonna start at index 1 of the array      a.reduce((start, end) => {        console.log(start, end);          r.push({          start,          end,        });          return end;      });        return r;    };      return func([]);  };    // Equivalent  const getPartsEquivalent = (a) => {    const r = [];      // Because there is no initial value    //    // Start will be the value at index 0 of the array    // The loop is gonna start at index 1 of the array    a.reduce((start, end) => {      console.log(start, end);        r.push({        start,        end,      });        return end;    });      return r;  };    var optimizedRoute = ['Bengaluru', 'Salem', 'Erode', 'Tiruppur', 'Coimbatore']    console.log(getPartsEquivalent(optimizedRoute));
.as-console-wrapper {    max-height: 100% !important;    top: 0;  }
like image 185
Nina Scholz Avatar answered Sep 19 '22 12:09

Nina Scholz