Map场景题
Sunny-117 opened this issue · comments
Map场景题
arr = [
{
name: "可乐",
categories: ["热门", "饮料"],
},
{
name: "苹果",
categories: ["热门", "食物"],
},
{
name: "洗衣液",
categories: ["生活用品"],
},
];
// [
// { name: "热门", categories: ["可乐", "苹果"] },
// { name: "饮料", categories: ["可乐"] },
// { name: "食物", categories: ["苹果"] },
// { name: "生活用品", categories: ["洗衣液"] },
// ];
function changeFormat(arr){
let res = [];
let map = new Map();
arr.forEach(item => {
let categories = item.categories;
categories.map(keyWord => {
if(!map.has(keyWord)){
map.set(keyWord, [item.name]);
}else{
map.get(keyWord).push(item.name);
}
})
})
map.forEach((val, key) => {
res.push({ name: key, categories: val})
})
return res;
}
console.log(changeFormat(arr))
const arrs = [
{
name: "可乐",
categories: ["热门", "饮料"],
},
{
name: "苹果",
categories: ["热门", "食物"],
},
{
name: "洗衣液",
categories: ["生活用品"],
},
];
let map = new Map();
const res = [];
for (const arr of arrs) {
const { name, categories } = arr;
for (const category of categories) {
if (!map.has(category)) map.set(category, [name]);
else {
let val = map.get(category);
val.push(name);
map.set(category, val);
}
}
}
map.forEach((key, val) => {
res.push({ name: val, categories: key });
});
console.log(res);
function process(arr) {
if (!Array.isArray(arr)) return;
let map = new Map();
let res = [];
arr.forEach(item => {
const categories = item.categories;
categories.map((category) => {
if (!map.has(category)) {
map.set(category, [].concat(item.name))
} else {
map.get(category).push(item.name)
}
})
})
map.forEach((value, key) => {
res.push({ name: key, categories: value })
})
return res;
}
console.log(process(arr));
const map = new Map();
let res2 = [];
for({name, categories} of arr){
for(let i = 0; i < categories.length; ++i){
const val = categories[i]
map.has(val) ? map.get(val).push(name) : map.set(val, [name]);
}
}
for (const [name, categories] of map) {
res2.push({name, categories});
}
let arr = [
{
name: '可乐',
categories: ['热门', '饮料'],
},
{
name: '苹果',
categories: ['热门', '食物'],
},
{
name: '洗衣液',
categories: ['生活用品'],
},
]
function changeFormat(arr) {
let map = new Map()
for (let i = 0; i < arr.length; i++) {
arr[i].categories.forEach((val, key) => {
let a = map.get(val)
a ? a.push(arr[i].name) : (a = [arr[i].name])
map.set(val, a)
})
}
let newArr = []
map.forEach((val, key) => {
newArr.push({ name: key, categories: val })
})
return newArr
}
function convey(data) {
let map = new Map()
for (let item of data) {
for (let cate of item.categories) {
if (!map.has(cate)) {
map.set(cate, {
name: cate,
categories: [item.name]
})
} else {
map.get(cate).categories.push(item.name)
}
}
}
return [...map.values()]
}