skip to Main Content

I need to see if an element is in another list or not but they are not in order and they are not equal size.

let list1 = [10 , 4 , 5]
let list 2 = [4 , 5]

I tried this but this only works if they are in same order.

  for(var i=0;i<=document.querySelectorAll('.datename').length;i++){

    if(document.querySelectorAll('.inputname')[i].value==document.querySelectorAll('.datename')[i].innerHTML){
        console.log(document.querySelectorAll('.other')[c].classList)
           document.querySelectorAll('.other')[c].classList.add('active2')
    }
}

2

Answers


  1. You can put all the element values into an array first, then use Array#includes to check for a match.

    let vals = Array.from(document.querySelectorAll('.inputname'), el => el.value);
    for (const el of document.querySelectorAll('.datename')) {
        if (vals.includes(el.textContent)) {
            // do something
        }
    }
    
    Login or Signup to reply.
  2. The possible solution you have tried is:

    const input = document.querySelectorAll('.input');
    const data = document.querySelectorAll('.data');
    
    for (let i = 0; i < input.length; i++) {
      const inputValue = input[i].value;
      
      if (Array.from(data).some(dateElement => dateElement.innerHTML === inputValue)) {
        console.log('Element ' + inputValue + ' is included in datename list.');
        // do something if the element is included, e.g.
        document.querySelectorAll('.other')[i].classList.add('active2');
      } else {
        console.log('Element ' + inputValue + ' is not included in datename list.');
      }
    }
    

    Or,

    If you want to check if data of an array contains in another array and if they are not same length then you can use the include() method.

    let list1 = [10, 4, 5];
    let list2 = [4, 5];
    
    for (let i = 0; i < list2.length; i++) {
      if (list1.includes(list2[i])) {
        console.log("Element " + list2[i] + " is in list1.");
      }
    }
    

    the output will be:

    //Element 4 is in list1.

    //Element 5 is in list1.

    check the sandbox: https://codesandbox.io/embed/sleepy-stitch-jb3c6l?fontsize=14&hidenavigation=1&theme=dark

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search