Javascript 如何合并重复数组?
输出:用户10、12和15喜欢您的故事ID 25Javascript 如何合并重复数组?,javascript,arrays,reactjs,Javascript,Arrays,Reactjs,输出:用户10、12和15喜欢您的故事ID 25 我想像上面那样显示输出。如何合并和显示与输出类似的内容。有什么想法吗?您需要创建一个哈希映射,请检查下面的代码片段: const allData=[ {名字:'约翰',故事:1}, {名字:'罗斯',故事:2}, {姓名:'泰勒',故事:1}, {名字:'吉米',故事:2}, {姓名:'Amanda',故事:3}, ]; 常量哈希={}; for(所有数据中的let数据){ if(data.story in hash)hash[data.sto
我想像上面那样显示输出。如何合并和显示与输出类似的内容。有什么想法吗?您需要创建一个哈希映射,请检查下面的代码片段:
const allData=[
{名字:'约翰',故事:1},
{名字:'罗斯',故事:2},
{姓名:'泰勒',故事:1},
{名字:'吉米',故事:2},
{姓名:'Amanda',故事:3},
];
常量哈希={};
for(所有数据中的let数据){
if(data.story in hash)hash[data.story]=[…hash[data.story],{…data}];
else散列[data.story]=[{…data}];
}
console.log(散列)代码>我无法评论。所以我写在这里
你想要
const data =
[{notification_id: 124, user_id: 10, story_id: 25, string: "liked on your story" }
{notification_id: 125, user_id: 12, story_id: 25, string: "liked on your story" }
{notification_id: 126, user_id: 15, story_id: 25, string: "liked on your story" }]
对吧?
这是我的解决方案
result = [
{
story_id : 25,
user_id : [10, 12, 15]
}
]
我正在通知小组工作。我需要合并将从数据库中提取的重复数组。所以我不知道会有多少ID。@ShahariarRahmanSajib我已经更新了我的答案,请检查它是否解决了您的问题problem@ShahariarRahmanSajib你核对我的答案了吗?这不是你想要的吗?
const data =
[{notification_id: 124, user_id: 10, story_id: 25, string: "liked on your story" }
{notification_id: 125, user_id: 12, story_id: 25, string: "liked on your story" }
{notification_id: 126, user_id: 15, story_id: 25, string: "liked on your story" }]
var result = data.reduce((res, item) => {
let storyID = item.story_id;
if (typeof res[storyID] == 'undefined') {
res[storyID] = {
story_id: storyID,
user_id: []
}
}
res[storyID].user_id.push(item.user_id);
return res;
}, []);
result = Object.values(result);