Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

标签整理分类题 #391

Open
DiF1202 opened this issue Jan 15, 2023 · 1 comment
Open

标签整理分类题 #391

DiF1202 opened this issue Jan 15, 2023 · 1 comment

Comments

@DiF1202
Copy link
Contributor

DiF1202 commented Jan 15, 2023

[
  {
    name: "可乐",
    categories: ["热门", "饮料"],
  },
  {
    name: "苹果",
    categories: ["热门", "食物"],
  },
  {
    name: "洗衣液",
    categories: ["生活用品"],
  },
];

[
  { name: "热门", categories: ["可乐", "苹果"] },
  { name: "饮料", categories: ["可乐"] },
  { name: "食物", categories: ["苹果"] },
  { name: "生活用品", categories: ["洗衣液"] },
];

function changeArr(data) {
  let newArr = [];
  let map = new Map();
  for (const item of data) {
    for (const cat of item.categories) {
      if (map.has(cat)) {
        map.set(cat, [...map.get(cat), item.name]);
      } else {
        map.set(cat, [item.name]);
      }
    }
  }
  for (const [key, value] of map) {
    let obj = {};
    obj.name = key;
    obj.categories = value;
    newArr.push(obj);
  }
  return newArr;
}
console.log(changeArr(arr));

此题来自面试真题
@Liu6625
Copy link

Liu6625 commented Oct 19, 2023

function changeKey(data){
  let newData = [];
  let map = new Map();
  data.forEach(item => {
    item?.categories.forEach(it => {
      map.set(it, map.has(it) ? [...map.get(it), item.name] : [item.name]);
    })
  });

  for (const [key, value] of map) {
    newData.push({ name: key, categories: value });
  }
  return newData;
}
console.log(changeKey(data));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants