0

I have a crazy array look like this:

const data = [
     [{ Name: 'Name 1', Block: [{Id: "1"}, {Id: "2"}] }],
     [{ Name: 'Name 2', Block: [{Id: "3"}, {Id: "4"}] }],
]

I want to map Block to a single array to look like this:

[  { Id: '1' },
   { Id: '2' },
   { Id: '3' }, 
   { Id: '4' }
]

I have tried doing like this:

const data = [
     [{ Name: 'Name 1', Block: [{Id: "1"}, {Id: "2"}] }],
     [{ Name: 'Name 2', Block: [{Id: "3"}, {Id: "4"}] }],
]


const idList = data.map(blockData => {
   return blockData[0].Block;
});

console.log(idList)

What did I do wrong?

3 Answers 3

2

.map will create a new item for every index of the old array. If your input array has 2 items, the output array will also only have 2 items - but you want 4 items, so .map won't work. Use flatMap instead, to flatten:

const data = [
     [{ Name: 'Name 1', Block: [{Id: "1"}, {Id: "2"}] }],
     [{ Name: 'Name 2', Block: [{Id: "3"}, {Id: "4"}] }],
];

const idList = data.flatMap(([{ Block }]) => Block);

console.log(idList)

flatMap is only implemented on newer implementations, though - otherwise, use a polyfill or a different method, like reduceing into an array:

const data = [
     [{ Name: 'Name 1', Block: [{Id: "1"}, {Id: "2"}] }],
     [{ Name: 'Name 2', Block: [{Id: "3"}, {Id: "4"}] }],
];

const idList = data.reduce((a, [{ Block }]) => a.concat(Block), []);

console.log(idList)

Sign up to request clarification or add additional context in comments.

Comments

0

your data is an array inside array so you should use map twice, Buth that will give you an array with 2 elements now you need to reduce or flatten the resulting array to get the desired output.

data.map(a=>{return a[0].Block.map(b=>{ return b})}).reduce((o, m) => [...m, ...o], [])

Comments

0

The most succinct way to do it would be with a reduce statement:

const reducer = (a, b) => a.concat(b[0].Block);
const idList = data.reduce(reducer, []);

This way it will be much clearer what you are trying to do.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.