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' ]]
CodePudding user response:
It can be something like this:
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' ]
]
const get_not_uniq_elements = arr => arr.filter(x => arr.indexOf(x) !== arr.lastIndexOf(x));
const flatt_2d_array = arr => arr.map(x => x.join('\t'));
const unflat_array = arr => arr.map(x => x.split('\t'));
var new_arr = flatt_2d_array(arr);
new_arr = get_not_uniq_elements(new_arr);
new_arr = unflat_array(new_arr);
console.log(new_arr);
Or the same algorithm in one line:
let new_arr = arr.map(x => x.join('\t'))
.filter((x,_,a) => a.indexOf(x) !== a.lastIndexOf(x))
.map(x => x.split('\t'));
CodePudding user response:
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 );