Home > Software engineering >  Simple array to objects with changing key
Simple array to objects with changing key

Time:06-09

I got a comma seperated list

var arr = [1,2,3,4]

and want it to be:

var new_arr = [
 {x:1, y:2},
 {x:3, y:4}
]

Struggeling how to get the key/value change done.

CodePudding user response:

You could use Array.reduce() to return the desired result.

If the element index is even, add a new item to the result, if not skip it.

const input = [1,2,3,4]
 
const result = input.reduce((acc, el, idx, arr) => { 
    return (idx % 2) ? acc : [...acc,  { x: el, y: arr[idx   1]} ];
}, []);
 
console.log('Result:', result);
.as-console-wrapper { max-height: 100% !important; }

CodePudding user response:

You could do something like the below:

First you map over your array and if the modulus value of your current iteration index does not equal to 0, you return an empty object (which you will then filter out at the end), otherwise you return a new object that grabs the current element on the iteration to y, and the previous element of the array (using index) to x

const x = [1,2,3,4,5]

const g = x.map((el, i) => {
  if(i%2) {
    return {
      x: x[i - 1],
      y: el
    }
  }
  return {}
}).filter(t => Object.keys(t).length)

console.log(g)

  • Related