Home > Software engineering >  Javascript - lodash or native array functions get first item
Javascript - lodash or native array functions get first item

Time:08-16

I have the following data

data: [
    [200, 3],
    [400, 4],
    [2344, 8],
    [34543, 2],
];
   

What I am trying to do with lodash or native filter/map functions is to create 2 arrays.

array1 = [200, 400, 2344, 34543];
array2 = [3, 4, 8, 2];

I have tried map, filter and lodash first with no luck.

CodePudding user response:

You can use lodash's _.unzip() and then get the two arrays via destructuring:

const data = [[200, 3], [400, 4], [2344, 8], [34543, 2]];

const [array1, array2] = _.unzip(data);

console.log(array1);
console.log(array2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG ljU96qKRCWh quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

CodePudding user response:

array1 = data.map(el=>el[0])
array2 = data.map(el=>el[1])

CodePudding user response:

Using .map() && .at() :

const data=  [
  [200, 3],
  [400, 4],
  [2344, 8],
  [34543, 2],
];

const unzip = arr => [ arr.map(x => x.at(0)),  arr.map(x => x.at(1)) ]

const [left, right] = unzip(data);

console.log(left);
console.log(right);

  • Related