【问题标题】:Split jsonarray into chunk arrays into another array将 jsonarray 拆分为块数组到另一个数组中
【发布时间】:2018-11-09 00:41:21
【问题描述】:

我正在尝试将子数组拆分为 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

}, [])

但是,对于我的输入,它不起作用。

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

【问题讨论】:

  • 您的perChunk2,但该示例显然每个都有3 对象...?此外,这可能会有所帮助:stackoverflow.com/a/44069560/519413
  • 您尝试的代码对我有用,只是因为您的perChunk = 2,它分成了每个包含 2 个项目而不是包含 3 个项目的块。
  • 在处理leftover elements 时,您的expected output 是什么?即array.length = 10chunk size = 8 因此leftover elements = 2
  • 我在我的答案中添加了一个更新,使用过滤器从数组中删除空对象

标签: javascript jquery arrays angularjs


【解决方案1】:

将数组分割成所需大小的块:

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);

【讨论】:

  • 对我来说效果很好。
【解决方案2】:

下面的 sn-p splits arrayschunks by size

Array.prototype.filter() 用于来自inputarrayomit 不需要的elements (even numbers)。

Array.prototype.slice 和一个for statement 组合起来创建chunks 没有mutating 原始input array

Leftovers 在相关时作为最终的chunk 包含在output 中。

// Input.
const input = [1, 2, 3, 4, 5, 6, 7, 8, 9].filter(x => x % 2)

// Chunk.
const chunk = (array, size) => {
  let output = []
  let i = 0
  const max = array.length + (array.length % size) + 1
  for (let j = size; j < max; j += size) {
    output.push(array.slice(i, j))
    i = j
  }
  return output
}

// Output / Proof.
console.log('chunk size: 1', chunk(input, 1))
console.log('chunk size: 3', chunk(input, 3))
console.log('chunk size: 5', chunk(input, 5))

【讨论】:

【解决方案3】:

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

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/

【讨论】:

  • 谢谢..但我不能接受所有的答案..所以我真的很抱歉
  • @Basha,没有人不能;)
  • 嗨@Manoj 小建议,如果元素值为空,如 title:"" 和 description:""... ex:[[{title:"a", desc:"ten"},{"title:"",desc:""}]]. 在这里我想输出为 [[{title:"a",desc:"ten"]] .. 任何建议请跨度>
  • 您可以在处理成块之前过滤数组。见这里w3schools.com/jsref/jsref_filter.asp
  • 但是,在这个提到的 w3schools url 中检查内部键值是可能的
【解决方案4】:

试试这样的:

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);

【讨论】:

  • 谢谢..但我不能接受所有的答案..所以我真的很抱歉
【解决方案5】:
// 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


你可以使用下划线的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"
    }
  ]
]

【讨论】:

  • 谢谢..但我不能接受所有的答案..所以我真的很抱歉
  • @Basha 别担心队友 :)
  • 如何从数组中删除元素,如果元素值是空的,如 title:"" 和 description:""... ex:[[{title:"a",desc:"ten"} ,{"title:"",desc:""}]]. 在这里我想输出为 [[{title:"a",desc:"ten"]] .. 任何建议请
  • @Basha 但你还想制作 2 块?
  • 我被分成了几块。但是,在保存时我保存为 3 个块......但由于值为空而引发错误。所以需要删除数组元素,如果标题为空
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多