从二维数组中删除唯一元素和 return 重复元素

Remove unique elements from a 2d array and return the repeating element

我想从二维数组中删除唯一元素并 return 重复元素。 例如:

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

输出应该是:

[[ 'Andrew', 'Male', 'Freshman', 'SD', 'Math', 'Lacrosse' ],
  [ 'Andrew', 'Male', 'Freshman', 'SD', 'Math', 'Lacrosse' ],
  [ 'Andrew', 'Male', 'Freshman', 'SD', 'Math', 'Lacrosse' ]]

可以是这样的:

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

或者一行中的相同算法:

let new_arr = arr.map(x => x.join('\t'))
  .filter((x,_,a) => a.indexOf(x) !== a.lastIndexOf(x))
  .map(x => x.split('\t'));

您可以在下面的演示中使用 Array#filter

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