Issue
I have 2 arrays:
First array is array of strings:
let array1 = ['value1', 'value2', 'value3', 'value4', 'value5']
second is array of objects that can vary, meaning sometimes I will have all the values sometimes only some and they will not be sorted. Something like this:
array2 = [
{
property1: 'value1',
property2: 42,
property3: 'some other value'
},
{
property1: 'value3',
property2: 342,
property3: 'some other value'
},
{
property1: 'value5',
property2: 422,
property3: 'some other value'
}
]
I need to make another array. If there is value1 from first array inside array2 I need to push to newly created array property2, if not I need to push 0. Order of the items needs to be the same as the array 1 meaning that in the end I will have an array that looks like this:
array3 = [42, 0, 342, 0, 422]
Thanks
I have looked up on stackoverflow but no solution worked for me
Solution
- Using
Array#reduce
, iterate overarray2
while updating aMap
where the key isproperty1
and the value isproperty2
- Using
Array#map
, iterate overarray1
to return the value of each item from the above Map,0
otherwise
const
array1 = ['value1', 'value2', 'value3', 'value4', 'value5'],
array2 = [ { property1: 'value1', property2: 42, property3: 'some other value' }, { property1: 'value3', property2: 342, property3: 'some other value' }, { property1: 'value5', property2: 422, property3: 'some other value' } ];
const valueMap = array2.reduce((map, { property1, property2 }) => map.set(property1, property2), new Map);
const array3 = array1.map(value => valueMap.get(value) ?? 0);
console.log(array3);
Answered By - Majed Badawi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.