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
CodePudding user response:
- 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);
CodePudding user response:
So you want to find all the property2
values where the property1
value exists in another array...
A forEach
with a push
to your result array (array3
) should do it:
const array1 = ['value1', 'value2', 'value3', 'value4', 'value5']
const 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'
}
]
let array3 = []
array2.forEach(item => {
if (array1.includes(item.property1)) {
array3.push(item.property2)
}
})
console.log(array3);
As other comments say, please remember to include the things you have tried when posting the question.
P.S: be careful when posting your code, there were some missing commas, making the syntax invalid