jchi2241
jchi2241

Reputation: 2226

Data manipulation with Lodash chaining or functional JS challenge

I have a set of data

const allNumbers = [
    { type: "smallNumbers", numbers: [1, 2, 3] },
    { type: "bigNumbers", numbers: [4, 5, 6] }
];

that needs to be molded into

[[1], [2], [3], [4, 5, 6]]

where numbers in objects of type smallNumbers are each individually wrapped in an array, and numbers in objects of type bigNumbers are simply left as is.

How would I do this with Lodash chaining (if possible) or plain functional JS?

Upvotes: 1

Views: 66

Answers (1)

Ori Drori
Ori Drori

Reputation: 191986

You can use _.flatMap() to iterate the objects, and use _.chunks() (default chunk size is 1) to split smallNumbers to subarrays:

const allNumbers = [
  { type: "smallNumbers", numbers: [1, 2, 3] },
  { type: "bigNumbers", numbers: [4, 5, 6] }
];

const result = _.flatMap(allNumbers, ({ type, numbers }) => 
  _.eq(type, 'smallNumbers') ? _.chunk(numbers) : [numbers]
);

console.log(JSON.stringify(result));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

Upvotes: 1

Related Questions