{id: 1, name: "item one", tags: ["music", "sport", "science"]},
{id: 2, name: "item two", tags: ["music"]},
{id: 3, name: "item three", tags: ["fun"]},
{id: 4, name: "item four", tags: ["sport", "science"]},
{id: 5, name: "item five", tags: []},
];
const fun = arr =>
arr.reduce((acc, item) => {
if (!item.tags.length) {
acc["without tag"] = acc["without tag"]
? [...acc["without tag"], item]
: [item];
return acc;
}
item.tags.forEach(I => {
return acc[I] = acc[I] ? [...acc[I], item] : [item];
});
return acc;
}, {});
console.log(fun(initialArray));
//([{music:[]},{...},{...}])
.reduce((acc, item) => { item.tags.forEach(tag => acc[tag] = (acc[tag] || []).concat(item)); if (item.tags.length === 0) { acc['untagged'] = (acc['untagged'] || []).concat(item); } return acc; }, {}); Это тебе надо что ли?
Обсуждают сегодня