简体   繁体   中英

How to filter the same sub-array from two-dimensional array in JavaScript

Suppose there are multiple sub-arrays with disordered integer elements, for example:

[[1, 2], [2, 1], [3, 2, 2], [2], [2, 1, 3], [2, 2, 3]]

I want to sort elements in every subarray and remove duplicates. So, after processing those data, the result should be the following:

[[1, 2], [2, 2, 3], [2], [1, 2, 3]]

How can I do it efficiently in JavaScript?

If your data is actually arrays of integers, you could do it like this

// ES6
let data = [[1, 2], [2, 1], [3, 2, 2], [2], [2, 1, 3], [2, 2, 3]];

// non-mutating sort function
function sort(x) { let y = x.slice(0); y.sort(); return y; }

let final = data.map(x => JSON.stringify(sort(x))).reduce((res, x) =>
  res.indexOf(x) === -1 ? res.concat(x) : res
, []).map(JSON.parse);

console.log(data);
console.log(final);

// [[1,2],[2,1],[3,2,2],[2],[2,1,3],[2,2,3]]
// [[1,2],[2,2,3],[2],[1,2,3]]

Notice that my solution does not mutate your input data unnecessarily (like the other solutions provided here)

If you need the ES5 code, here you go

// ES5
var data = [[1, 2], [2, 1], [3, 2, 2], [2], [2, 1, 3], [2, 2, 3]];

// non-mutating sort function
function sort(x) {
  var y = x.slice(0);y.sort();return y;
}

var final = data.map(function (x) {
  return JSON.stringify(sort(x));
}).reduce(function (res, x) {
  return res.indexOf(x) === -1 ? res.concat(x) : res;
}, []).map(JSON.parse);

console.log(data);
console.log(final);

// [[1,2],[2,1],[3,2,2],[2],[2,1,3],[2,2,3]]
// [[1,2],[2,2,3],[2],[1,2,3]]

you can try this: first sort them then remove the duplicates.

 var x=[[1, 2], [2, 1], [3, 2, 2], [2], [2, 1, 3], [2, 2, 3]]; for(i in x){ x[i].sort(); } b = uniqBy(x, JSON.stringify) document.getElementById("data").innerHTML=JSON.stringify(b); function uniqBy(a, key) { var seen = {}; return a.filter(function(item) { var k = key(item); return seen.hasOwnProperty(k) ? false : (seen[k] = true); }) } 
 <div id="data"></div> 

First, we need to sort your subarrays out. It is easy, because there is a built-in JavaScript function sort() :

 var arr = [[1, 2], [2, 1], [3, 2, 2], [2], [2, 1, 3], [2, 2, 3]]; arr.forEach(function(subarr) { subarr.sort(); }); document.body.innerHTML = JSON.stringify(arr); 

Now, we need to remove duplicates. There are two ways to do this - proper and hacky. I will describe the hacky one. To compare two arrays, you can simply compare their string representations:

 var arr = [[1, 2], [2, 1], [3, 2, 2], [2], [2, 1, 3], [2, 2, 3]]; arr.forEach(function(subarr) { subarr.sort(); }); var arrStrings = []; arr = arr.filter(function(subarr) { var stringified = JSON.stringify(subarr); // or simply .toString() if (arrStrings.indexOf(stringified) === -1) { arrStrings.push(stringified); return true; } else { return false; } }); document.body.innerHTML = JSON.stringify(arr); 

There are many non-hacky and proper solutions to compare arrays, you can read this StackOverflow article and choose the one you like.

Let's add another solution into the mix

 var arr = [[1, 2], [2, 1], [3, 2, 2], [2], [2, 1, 3], [2, 2, 3]]; var temp = {}; var updated = arr.reduce(function(prev, arr){ var adj = arr.slice(0).sort(); if (!temp[adj.join(",")]) { prev.push(adj); temp[adj.join(",")] = true; } return prev; },[]); console.log(JSON.stringify(updated)); 

Just use this javascript:

var arr = [[1, 2], [2, 1], [3, 2, 2], [2], [2, 1, 3], [2, 2, 3]];

function sortArray(array) {
  var count = array.length;
  var sorted = array.sort();
  var equal = true;

  for (var i=0;i<count;i++) {
    if (array[i].length > 1)
      array[i].sort();
  }
  array.sort().sort();

  for (var i=0;i<count;i++) {
    if (array[i] && array[i+1]) {
      for (var j=0, len=array[i].length; j<len; j++) {
        if (array[i][j] !== array[i+1][j])
          equal = false;
      }
      if (equal)
        array.splice(i,1);
      equal = true;
   }

  }

  console.log(array);
 }

 sortArray(arr);

Hope that helps!!

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