create new arrays for repeating elements in javascript

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

提交回复
热议问题