0

I Have next map:

 const filter = new Map();

  filter.set('a1', {
    Day: 55,
    Type: 1,
  });

  filter.set('a2', {
    Day: 2,
    Type: 3,
  });

And next Array:

Data = [
    {
      points: 1,
      event: 'a1',
    },
    {
      points: 2,
      event: 'a2',
    },
  ]

I am new in JS, so it is not clear for me, how I can merge these by event parameter? Expected output should be Map:

   result = ['a1',
    {
      points: 1,
      Day: 55,
      Type: 1,
    }],
    ['a2',
    {
      points: 2,
      Day: 2,
      Type: 3,
    }],
1
  • Try to do it yourself: loop through result using forEach, get event value, if filter has that value by key, get that and set points out of list item, 4-5 lines of code Commented Jul 22, 2020 at 10:26

2 Answers 2

3

you don't need reduce here. better use map with es6 spread ... operator for merging,

const filter = new Map();

filter.set('a1', {
  Day: 55,
  Type: 1,
});

filter.set('a2', {
  Day: 2,
  Type: 3,
});

const Data = [{
    points: 1,
    event: 'a1',
  },
  {
    points: 2,
    event: 'a2',
  },
]

const result = Data.map(o => [o.event, {
  points: o.points,
  ...filter.get(o.event)
}]);

console.log(result);

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

Comments

2

You could do something like the following:

const filter = new Map();

filter.set("a1", {
  Day: 55,
  Type: 1
});
filter.set("a2", {
  Day: 2,
  Type: 3
});

const data = [
  { points: 1, event: "a1" },
  { points: 2, event: "a2" }
];

const final = data.reduce((accumulator, item) => {
  // use destructing assignment to unpack values from the object
  const { event, points } = item;
  
  // get the appropriate event from the `filter` map by its event id
  const details = filter.get(event);

  // return a new array with the existing elements in `accumulator`
  // by using the `spread syntax` and append a new item/array
  // that has the `event` id in the first place, and an object
  // with the rest of the details in second place
  return [
    ...accumulator,
    [
      event,
      {
        points,
        ...details
      }
    ]
  ];
  // start with an empty array
}, []);

console.log(final);

References:

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.