create new arrays for repeating elements in javascript

前端 未结 3 1635
挽巷
挽巷 2021-01-25 07:07

I have a JavaScript array with 8 elements and some elements are repeating. I want to create separate arrays for identical elements.

example: original a

相关标签:
3条回答
  • 2021-01-25 07:21

    var arr = [1,1,1,3,3,1,2,2];
    
    var hash = Object.create(null);
    
    var result = arr.reduce(function(r, n) {
      if(!hash[n]) {
        hash[n] = [];
        r.push(hash[n]);
      }
      
      hash[n].push(n);
      
      return r;
    }, []);
    
    console.log(result);

    And an ES6 solution that uses Map, and spread:

    const arr = [1,1,1,3,3,1,2,2];
    
    const result = [...arr.reduce((r, n) =>
      r.set(n, (r.get(n) || []).concat(n)),
    new Map()).values()];
    
    console.log(result);

    0 讨论(0)
  • 2021-01-25 07:24

    Let's assume you want the resulting arrays to be properties on an object keyed by the value they represent. You just loop through the array, creating or adding to the arrays on the object properties as you go:

    var array=[1,1,1,3,3,1,2,2];
    var result = {};
    array.forEach(function(entry) {
      (result[entry] = result[entry] || []).push(entry);
    });
    console.log(result);

    That's a bit dense, here's a clearer version:

    var array=[1,1,1,3,3,1,2,2];
    var result = {};
    array.forEach(function(entry) {
      var subarray = result[entry];
      if (!subarray) {
        subarray = result[entry] = [];
      }
      subarray.push(entry);
    });
    console.log(result);

    0 讨论(0)
  • 2021-01-25 07:27

    You could use a hash table as reference to the sub arrays for the collection.

    var array = [1, 1, 1, 3, 3, 1, 2, 2],
        result = [];
    
    array.forEach(function (a) {
        a in this || result.push(this[a] = []);
        this[a].push(a);
    }, Object.create(null));
    
    console.log(result);

    0 讨论(0)
提交回复
热议问题