将jsonarray拆分为块数组到另一个数组中

时间:2018-05-30 08:31:24

标签: javascript jquery arrays angularjs

我正在尝试将子数组拆分为3个内部数组的块。

前:

[{
  title: "asd",
  description: "asd"
}, {
  title: "asz",
  description: "sd"
}, {
  title: "ws",
  description: "sd"
}, {
  title: "re",
  description: "sd"
}, {
  title: "32",
  description: "xxs"
}, {
  title: "xxc",
  description: "11"
}]

我想将上层数组转换为下面的块

[
  [{
    title: "asd",
    description: "asd"
  }, {
    title: "asz",
    description: "sd"
  }, {
    title: "ws",
    description: "sd"
  }],
  [{
    title: "re",
    description: "sd"
  }, {
    title: "32",
    description: "xxs"
  }, {
    title: "xxc",
    description: "11"
  }]
]

我尝试了一些像这样的示例,但它对这个数组['a','b','c','d','e']工作正常。下面是我试过的代码,

perChunk = 2 // items per chunk    

inputArray = ['a', 'b', 'c', 'd', 'e']

inputArray.reduce((resultArray, item, index) => {
  const chunkIndex = Math.floor(index / perChunk)

  if (!resultArray[chunkIndex]) {
    resultArray[chunkIndex] = [] // start a new chunk
  }

  resultArray[chunkIndex].push(item)

  console.log(resultArray)
  return resultArray

}, [])

但是,根据我的意见,它不起作用。

请建议我如何实现这个目标

5 个答案:

答案 0 :(得分:2)

您可以将数组拆分为给定数量的块

split(arr, n) {
        var res = [];
        while (arr.length) {
            res.push(arr.splice(0, n));
        }
        return res;
    }

<强>用法

 var arrayFregments = split(myArray, 3); //no of chunks
 var requests = arrayFregments.reduce((promiseChain, item) => {
            return promiseChain.then(() => new Promise((resolve) => {
                 asyncFunction(item, resolve); //some async function
            }));
        }, Promise.resolve());

 requests.then(() => {
               // after requests has been completed.
            });

<强>更新

如果要消除空数据对象,则可以使用过滤器

mainList = mainList.filter(function(item){
        return item.title.trim().length>0 && item.description.trim().length>0

});
console.log(mainList)

示例 - http://jsfiddle.net/zj1pe7q3/3/

答案 1 :(得分:2)

将数组拆分为所需大小的块:

&#13;
&#13;
var arr = [{
  title: "asd",
  description: "asd"
}, {
  title: "asz",
  description: "sd"
}, {
  title: "ws",
  description: "sd"
}, {
  title: "re",
  description: "sd"
}, {
  title: "32",
  description: "xxs"
}, {
  title: "xxc",
  description: "11"
}]

var i, j, resArray=[], chunk = 2;
for (i = 0, j = arr.length; i < j; i += chunk) {
  resArray.push(arr.slice(i, i + chunk));
}

console.log(resArray);
&#13;
&#13;
&#13;

答案 2 :(得分:2)

splits arrays之后的chunks size以下代码段。

Array.prototype.filter()用于来自omit elements的{​​{1}}不受欢迎的even numbers input}。

Array.prototype.slicefor statement合并后创建array chunks原始mutating input

在相关时,

array被列为Leftovers中的最终chunk

&#13;
&#13;
output
&#13;
&#13;
&#13;

答案 3 :(得分:1)

// Chunk a single array into multiple arrays, each containing `count` or fewer
  // items.
function chunk(array, count) {
    if (count == null || count < 1) return [];
    var result = [];
    var i = 0, length = array.length;
    while (i < length) {
      result.push(Array.prototype.slice.call(array, i, i += count));
    }
    return result;
  };

用法:

var newList = chunk(mainList, 2);

Demo Fiddle

OR

您可以使用chunk下划线或lodash

var mainList = [
  {
    "title": "asd",
    "description": "asd"
  },
  {
    "title": "asz",
    "description": "sd"
  },
  {
    "title": "ws",
    "description": "sd"
  },
  {
    "title": "re",
    "description": "sd"
  },
  {
    "title": "32",
    "description": "xxs"
  },
  {
    "title": "xxc",
    "description": "11"
  }
];

var newList = _.chunk(mainList, 2);

输出:

[
  [
    {
      "title": "asd",
      "description": "asd"
    },
    {
      "title": "asz",
      "description": "sd"
    }
  ],
  [
    {
      "title": "ws",
      "description": "sd"
    },
    {
      "title": "re",
      "description": "sd"
    }
  ],
  [
    {
      "title": "32",
      "description": "xxs"
    },
    {
      "title": "xxc",
      "description": "11"
    }
  ]
]

答案 4 :(得分:1)

尝试类似的东西:

const chucnk = (array, chunckSize) =>
  array.reduce(
    (a, b, i, g) =>
      !(i % chunckSize) ? a.concat([g.slice(i, i + chunckSize)]) : a,
    []
  );

const array = [{
  title: "asd",
  description: "asd"
}, {
  title: "asz",
  description: "sd"
}, {
  title: "ws",
  description: "sd"
}, {
  title: "re",
  description: "sd"
}, {
  title: "32",
  description: "xxs"
}, {
  title: "xxc",
  description: "11"
}]

chunck(array,3);