Home > front end >  finding all matches and returning values from array object
finding all matches and returning values from array object

Time:10-24

var sel = document.querySelectorAll('ul li a')
sel[0] == // ELEMENT WITH div.bottom ul li a.box
sel[1] == // ELEMENT WITH div.head ul li a.box

var list = [
    {css: 'a span', val:'1st'},
    {css: 'div.bottom ul a', val:'2nd'},
    {css: 'div.head li > a.box', val:'3rd'},
    {css: 'div.head li a', val:'4th'}
]

//desired result 
"sel[0] matches 2nd"
"sel[1] matches 3rd,4th"

I'm trying to find all css selectorAll matches from a list. I know I can use nested for loop and loop through both selectors and list in this way

for (var i = 0; i < list.length; i  ) {
    if (sel[0].matches(list[i].css)) {
      console.log(list[i].val);
    }
  }

but trying to find better solution without using nested for loop. How can I improve this code?

CodePudding user response:

Use the filter() method to get all matching elements of an array.

sel.forEach((el, i) => {
    let matches = list.filter(item => el.matches(item.css));
    if (matches.length > 0) {
        console.log(`sel[${i}] matches ${matches.map(item => item.val).join(',')}`);
    }
}
  • Related