create new arrays for repeating elements in javascript

前端 未结 3 1636
挽巷
挽巷 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);

提交回复
热议问题