Home > Software design >  render out a list of elements from a list in Javascript React
render out a list of elements from a list in Javascript React

Time:08-17

i have two lists. I only want to render out the objects of list2 whose id == 2,3,5 & 7. in my project the lists are too big, which is why it's very important that the solution is very optimized & doesn't take much time.! thanks in advance

const list1 = [2,3,5,7]
const list2 = [{id:1,name:Ronaldo},{id:2,name:Johny Depp},{id:3,name:Mr.Bean},{id:4,name:Messi},{id:5,name:Jennifer Anniston},{id:6,name:Ted Mosby},{id:7,name:Regner},{id:8,name:Thor}]

CodePudding user response:

Use a filter - if the list 2 item id is in list 1 render it, if not ignore it:

const listToRender = list2.filter(item => list1.indexOf(item.id) > -1)

CodePudding user response:

We can do it in O(N) time if we put the values of list1 into a set for O(1) lookup:

function filterList(list1, list2) {
    let itemSet = new Set(list1);
    let listOutput = list2.filter(x => itemSet.has(x.id));
    return listOutput;
}
  • Related