展平数组并将索引保​​持为其位置值

时间:2015-08-13 15:21:30

标签: javascript angularjs lodash

$scope.data = [[1,2,3], [1,5,6,7], [2,3]];

我会用 _.flatten($scope.data)所以scope.data就像是

$scope.data = [1,2,3,1,5,6,7,2,3];

但是我想在每个被展平的元素中保留数组的索引

所以我会有类似的东西:

$scope.data = [{value:1, index:1},
                  {value:2, index:1},
                  {value:3, index:1},
                  {value:1, index:2},
                  {value:5, index:2},
                  {value:6, index:2},
                  {value:7, index:2},
                  {value:2, index:3}
                  {value:3, index:3}];

3 个答案:

答案 0 :(得分:2)

你可以循环遍历原始数组:

function flatten(arr)
{
    var returnArray = new Array();
    for(var i = 0; i < arr.length; i++)
    {
        for(var j = 0; j < arr[i].length; j++)
        {
            returnArray.push({"value" : arr[i][j], "index" : i});
        }
    }
    return returnArray;
}

输出:

enter image description here

答案 1 :(得分:1)

var input = [[1, 2, 3], [1, 5, 6, 7], [2, 3]],
    output;

output = Array.prototype.concat.apply([], input.map(function(arr, idx) {
        return arr.map(function(el) {
            return { "value": el, "index": (idx + 1) };
        });
    })
);

console.log(JSON.stringify(output));
// [{"value":1,"index":1},{"value":2,"index":1},{"value":3,"index":1},{"value":1,"index":2},{"value":5,"index":2},{"value":6,"index":2},{"value":7,"index":2},{"value":2,"index":3},{"value":3,"index":3}]

fiddle

答案 2 :(得分:0)

您可以采用纯粹的功能性方式

  var data = [[1,2,3], [1,5,6,7], [2,3]];

  function flat(arr){
    return arr.reduce(function(result, current, index){
      return result.concat(current.map(function(elm){
        return {value: elm, index: index + 1}
      }))
    }, []);
  }

console.log(flat(data));