JavaScript flattening an array of arrays of objects

前端 未结 10 1605
名媛妹妹
名媛妹妹 2020-11-29 06:15

I have an array which contains several arrays, each containing several objects, similar to this.

[[object1, object2],[object1],[object1,object2,object3]]


        
相关标签:
10条回答
  • 2020-11-29 07:11

    Using ES6 Spread Operator

    Array.prototype.concat(...searchData)

    OR

    [].concat(...searchData)

    0 讨论(0)
  • 2020-11-29 07:13

    I've noticed that people are using recursions which are not cost friendly, especially with new ES6 standards giving us the power of spread operators. When you're pushing the items into the master array just use ... and it will automatically add flattened objects. Something like

    array.push(...subarray1)    // subarray1 = [object1, object2]
    array.push(...subarray2)    // subarray2 = [object3]
    array.push(...subarray3)    // subarray3 = [object4,object5, object6]
    // output -> array = [object1, object2, object3, object4, object5, object6]
    
    0 讨论(0)
  • 2020-11-29 07:15
    let functional = {
        flatten (array) {
            if (Array.isArray(array)) {
                return Array.prototype.concat(...array.map(this.flatten, this));
            }
    
            return array;
        }
    };
    
    functional.flatten([0, [1, 2], [[3, [4]]]]); // 0, 1, 2, 3, 4
    
    0 讨论(0)
  • 2020-11-29 07:15

    let nestedArray = [[1, 2], [3, 4], [5, 6]];
    
    let flattenArray = function(nestedArray) {
    
    	let flattenArr = [];
      
    	nestedArray.forEach(function(item) {
      	flattenArr.push(...item);
      });
      
      return flattenArr;
    };
    
    console.log(flattenArray(nestedArray)); // [1, 2, 3, 4, 5, 6]

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