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

Javascript Array Object, return result in correct order

I have a created a array object. To simplify it I have just kept two fields, id and name.

I want to filter the mainArray and return the result in the order of the [3,9,1] as seen in the filterArray array object where with the code I am using sorts this to [1,3,9].

I have scaled down the array for simplicity.

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

mainArray = [
    { id: 1, name: 'AC Milan' },
    { id: 2, name: 'Juventus' },
    { id: 3, name: 'AS Roma' },
    { id: 4, name: "Napoli"},
    { id: 9, name: "Inter Milan"}
];

filterArray = [
    { id: 3 },
    { id: 9 },
    { id: 1 }
];

filteredArray = mainArray.reduce((acc, item, index) => {
    if(filterArray.some(filterItem => filterItem.id === item.id)) {
        // console.log(index);
        acc.push(item);
    }
    return acc;
}, []);

    
for(n=0; n<=filteredArray.length; n++){
    document.write(filteredArray[n].id+" - "+filteredArray[n].name+"<br/>");
};
    

>Solution :

I always like to make an object by id for easy access.

mainArray = [
    { id: 1, name: 'AC Milan' },
    { id: 2, name: 'Juventus' },
    { id: 3, name: 'AS Roma' },
    { id: 4, name: "Napoli"},
    { id: 9, name: "Inter Milan"}
];

filterArray = [
    { id: 3 },
    { id: 9 },
    { id: 1 }
];

dict = mainArray.reduce((acc, item) => {
  acc[item.id] = item;
  return acc;
}, {});

filteredArray = filterArray.map(item => dict[item.id])

for (n = 0; n < filteredArray.length; n++) {
  document.write(filteredArray[n].id + " - " + filteredArray[n].name + "<br/>");
};
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