在数组中重复如何删除它 - JavaScript

Duplicate in array to how to remove it - JavaScript

基本上我有一个数组,像这样:

const companies = [
  {
    name: "Company One",
    category: "Finance, Finance, Technology, Auto, Same, Same, same",
    start: 1981,
    end: 2004
  }
]

在类别中,我想编写一个 .map 或 if 语句来查找与值匹配的值 if so 删除所有额外的值(例如 Same)并只保留它的一个实例。

到目前为止我所做的是:

const newSingles = companies.map(function(company) {
  if (company.category === company.category) {
    console.log("cats match remove and leave one");
    //This is where I am stuck?!
  };
});

这让我有点发疯,因为我打算使用 .pop() 但不确定如何使用。接下来我可以尝试什么?

尝试 Array.filter(),不要在 .map() 中使用 if 语句

也许这会对您有所帮助:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

您应该拆分类别,并且需要在类别数组列表中找到唯一值。试试类似的东西;

var category = ["Finance", "Finance", "Technology", "Auto", "Same", "Same", "same" ];
var uniques= category.filter((item, i, ar) => ar.indexOf(item) === i);

console.log(uniques);

稍作改动,您的新实现将如下所示;

const newSingles = companies.map(function(company) {
const category = company.category.filter((item, i, ar) => ar.indexOf(item) === i);
  return {
   ...company,
   category
  }
});

这是您的新结果;

[
  {
    name: "Company One",
    category:[ "Finance", "Technology", "Auto", "Same", "same"],
    start: 1981,
    end: 2004
  }
]

非常感谢大家的帮助,能得到帮助真是太好了!

如果我将所有类别放在它们自己的数组中:

const companies = [
  {
    name: "Company One",
    category: ["Finance", "Finance", "Technology", "Auto", "Same",
               "Same"],
    start: 1981,
    end: 2004
  }
]; 

然后这样做:

companies.map(it => 
    it.category = it.category.reduce((previous, currItem) => {
        if (!previous.find(
                    x => x.toLowerCase() === currItem.toLowerCase()))
            previous.push(currItem);
        return previous;
    }, []));

这给了我以下输出:

[
  {
    name: 'Company One',
    category: [ 'Finance', 'Technology', 'Auto', 'Same' ],
    start: 1981,
    end: 2004
  }
]

再次感谢您的帮助:)