Home > front end >  Map and pushing arrays
Map and pushing arrays

Time:09-29

I am quite new to React and TypeScript. I have some icons I want to map like this:

const iconLookups =
    dataPackNumber1.map(
      (e) =>
        e.icon_prefix &&
        e.icon_name && {
          prefix: e.icon_prefix,
          iconName: e.icon_name,
        },
    ) as IconLookup[];

Further I have more icons under dataPackNumber2 and dataPackNumber3 that look the same and I would like to map them all at once. Another way I was thinking of was to map them seperately and then to push them into the iconLookups array, but I cant seem to figure out how.

iconLookups.push(
    dataPackNumber.map(
      (e) =>
        e.icon_prefix &&
        e.icon_name && {
          prefix: e.icon_prefix,
          iconName: e.icon_name,
        },
    ) as IconLookup[];) 

and

const iconLookups =
    dataPackNumber1 && dataPackNumber2 && dataPackNumber3.map(
      (e) =>
        e.icon_prefix &&
        e.icon_name && {
          prefix: e.icon_prefix,
          iconName: e.icon_name,
        },
    ) as IconLookup[];

The code doesn't provide me errors, but on the UI I can see that only the last provided dataPackNumber will be actually rendered, if I chain them with &&.

Can someone please enlighten me?

CodePudding user response:

.push() will push one element onto the array. In your case, that element is an entire array. Resulting in a structure like this:

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

&& will likely just resolve to the last expression, which in your case is just dataPackNumber3.map(/*...*/).

One way to combine all three is with the spread syntax. Structurally it would be something like:

let result = [...array1, ...array2, ...array3];

So in your case it might be:

const iconLookups = [
  ...dataPackNumber1,
  ...dataPackNumber2,
  ...dataPackNumber3.map(/*...*/)
] as IconLookup[];

Edit: As pointed out in a comment below, .push() can indeed add multiple elements to an array when added as multiple arguments:

arr1.push(3, 4, 5);

Which means the spread syntax can also work there:

const iconLookups = dataPackNumber1.map(/*...*/) as IconLookup[];
iconLookups.push(...dataPackNumber2.map(/*...*/));
iconLookups.push(...dataPackNumber3.map(/*...*/));
  • Related