'Remove unique elements from a 2d array and return the repeating element
I want to remove unique elements from a 2d array and return the repeating elements. For Ex:
let arr = [ [ 'Alexandra', 'Female', 'Senior', 'CA', 'English', 'Drama Club' ],
[ 'Andrew', 'Male', 'Freshman', 'SD', 'Math', 'Lacrosse' ],
[ 'Andrew', 'Male', 'Freshman', 'SD', 'Math', 'Lacrosse' ],
[ 'Andrew', 'Male', 'Freshman', 'SD', 'Math', 'Lacrosse' ],
[ 'Benjamin', 'Male', 'Senior', 'WI', 'English', 'Basketball' ],
[ 'Carl', 'Male', 'Junior', 'MD', 'Art', 'Debate' ]]
Output should be:
[[ 'Andrew', 'Male', 'Freshman', 'SD', 'Math', 'Lacrosse' ],
[ 'Andrew', 'Male', 'Freshman', 'SD', 'Math', 'Lacrosse' ],
[ 'Andrew', 'Male', 'Freshman', 'SD', 'Math', 'Lacrosse' ]]
Solution 1:[1]
You can use Array#filter
as in the demo below.
const arr = [ [ 'Alexandra', 'Female', 'Senior', 'CA', 'English', 'Drama Club' ],
[ 'Andrew', 'Male', 'Freshman', 'SD', 'Math', 'Lacrosse' ],
[ 'Andrew', 'Male', 'Freshman', 'SD', 'Math', 'Lacrosse' ],
[ 'Andrew', 'Male', 'Freshman', 'SD', 'Math', 'Lacrosse' ],
[ 'Benjamin', 'Male', 'Senior', 'WI', 'English', 'Basketball' ],
[ 'Carl', 'Male', 'Junior', 'MD', 'Art', 'Debate' ]],
output = arr.filter(
([firstName,gender,classOf,state,course,club],i,a) =>
a.find(
([fn,g,co,st,cs,cb],j) =>
i !== j && fn === firstName &&
g === gender &&
co === classOf &&
st === state &&
cs === course &&
cb === club
)
);
console.log( output );
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | PeterKA |