简体   繁体   中英

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' ]]

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'));

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 );

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