![](/img/trans.png)
[英]How can i create a function with two-dimensional arrays and adding elements in the same position?
[英]In JavaScirpt, how do I filter the elements of the same field in two arrays and return a new two-dimensional array
這是一個例子:
我想根據 arry1 中的字段重新組合 arry2
var arry1 = [
{id: 1, parentId: 0, name: "phone"},
{id: 2, parentId: 1, name: "nick"}
];
var arry2 = [
{id: 7, parentId: 0, name: "phone_item1"},
{id: 8, parentId: 1, name: "phone_item2"},
{id: 9, parentId: 0, name: "nick_item1"},
{id: 10, parentId: 1, name: "nick_item2"}
];
let newArrys = arry1.filter((item)=>{
return leve_two.indexOf(arry2.parentId) == -1
})
我想返回一個二維數組:
[[
{id: 7, parentId: 0, name: "phone_item1"},
{id: 9, parentId: 0, name: "nick_item1"}
],[
{id: 8, parentId: 1, name: "phone_item2"},
{id: 10, parentId: 1, name: "nick_item2"}
]]
我試過Array.filter
等等。
你能幫助我嗎?
您可以使用filter()
方法和Object.values()
來獲得所需的輸出:
const arr1 = [ {id: 1, parentId: 0, name: "phone", level: 0, productCount: 0}, {id: 2, parentId: 1, name: "nick", level: 0, productCount: 0} ]; const arr2 = [ {id: 7, parentId: 0, name: "phone_item1", level: 1, productCount: 0}, {id: 8, parentId: 1, name: "phone_item2", level: 1, productCount: 0}, {id: 9, parentId: 0, name: "nick_item1", level: 1, productCount: 0}, {id: 10, parentId: 1, name: "nick_item2", level: 1, productCount: 0} ]; const filterIds = arr1.map(({ parentId }) => parentId); const arr3 = Object.values(arr2.reduce((r, c) => { r[c.parentId] = r[c.parentId] || []; r[c.parentId].push(c); return r; }, {})); console.log(arr3);
.as-console-wrapper { max-height: 100% !important; top: 0; }
看起來就像按parentId
將arry2
分組而arry1
看起來沒用🤔
為此使用一些庫。 例如 Ramda 方式:
const result = R.pipe(
R.groupBy(R.prop("parentId")),
R.toPairs,
R.map(R.last)
)(arry2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.