简体   繁体   中英

filtering 2 arrays for unique elements

I write a function that receives 2 arrays and returns an array that has elements that exist in both arrays. For example, if I pass [6,7,8,9] and [1,8,2,6], it should return [6,8].

My aim is not to use loops here.

I use this code:

const uniqueElements= (arr1, arr2) => {
return arr1.filter(it1=> arr2.filter((it2) => it2===it1).length>0)
}

However, if there are duplicate elements in arrays (eg [6,7,8,9,6] and [1,8,2,6,6]), it returns [6, 8, 6].

How should I mend my code so that it would return only unique elements without duplicates? Is it possible without using loops?

For your scenario use this -

constant uniqueElements= (arr1, arr2) => {
return Array.from(new Set(arr1.filter(it1=> arr2.filter((it2) => it2===it1).length>0)))
}

Hope this helps

Solution using Set from https://2ality.com/2015/01/es6-set-operations.html :

const uniqueElements = (arr1, arr2) => {
    const a = new Set(arr1);
    const b = new Set(arr2);
    const intersection = new Set(
        [...a].filter(x => b.has(x)));
    return Array.from(intersection);
}

If you just want to get unique value which appears on both of the array, you just first change both of the array's to Set, loop through one Set and check if it's present on other or not, if it present return true from filter else return false,

 const uniqueElements= (arr1, arr2) => { let set1 = new Set(arr1) let set2 = new Set(arr2) return [...set1].filter(it1=> set2.has(it1)) } console.log(uniqueElements([6,7,8,9],[1,8,2,6])) console.log(uniqueElements([6,7,8,9,6],[1,8,2,6,6]))

Ref to read about Set Set MDN

Simply you can just use Array#some() method to write the condition inside your Array#filter() method 's callback:

const uniqueElements = (arr1, arr2) => {
  let viewed = [];
  return arr1.filter(it1 => {
    let found = arr2.some((it2) => it2 === it1) && viewed.indexOf(it1) == -1;
    viewed.push(it1);
    return found;
  });
}

Note:

This doesn't take duplicates, with the use of viewed array and viewed.indexOf(it1) == -1 condition.

Demo:

 const uniqueElements = (arr1, arr2) => { let viewed = []; return arr1.filter(it1 => { let found = arr2.some((it2) => it2 === it1) && viewed.indexOf(it1) == -1; viewed.push(it1); return found; }); } let a1 = [6,7,8,9,6]; let a2 = [1,8,2,6,6]; console.log(uniqueElements(a1, a2));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM