Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

compare array of object with array of strings

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 over array2 while updating a Map where the key is property1 and the value is property2
  • Using Array#map, iterate over array1 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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading