skip to Main Content

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.

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/>");
};
    

2

Answers


  1. 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/>");
    };
    Login or Signup to reply.
  2. You can combine map and find:

    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 = filterArray.map(item => mainArray.find(x => x.id === item.id));
    
    for (n = 0; n < filteredArray.length; n++) {
      document.write(filteredArray[n].id + " - " + filteredArray[n].name + "<br/>");
    };
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search