Javascript find index of missing elements of two arrays

前端 未结 4 410
[愿得一人]
[愿得一人] 2021-01-28 18:34

I have the following JavaScript where I have some lists:

var deleteLinks = $(\".remove-button .remove-from-cart\");
deleteLinks.on(\'click\', function(ev){
            


        
4条回答
  •  感情败类
    2021-01-28 19:38

    Assuming that you have unique elements in an array A and only one occurrence in the array B. We can just use set to add all the elements of array A and remove the elements from the set when you iterate over Array B. Use findIndex to look up for elements remaining in the set.

    const a = [1,2,3,4,5];
    const b = [2,1,5,4];
    let set = new Set();
    a.forEach(ele => set.add(ele));
    b.forEach(ele => {
      if(set.has(ele)){
        set.remove(ele);
      }
    });
    let res = [];
    for(let s of set) {
      if(a.findIndex(s) !== -1) {
        res.push({
         arr:  a,
         pos: a.findeIndex(s)
        });
      }else {
        res.push({
         arr:  b,
         pos: b.findeIndex(s)
        });
      }
    }
    

    The res array contains the index and the array in which the element is present.

提交回复
热议问题