基本上我有一个数组,如下所示:
const companies = [
{
name: "Company One",
category: "Finance, Finance, Technology, Auto, Same, Same, same",
start: 1981,
end: 2004
}
]在category中,我想编写一个.map或if语句来查找与值匹配的值,如果是这样的话,删除所有额外的值(例如相同),只保留一个实例。
到目前为止,我所做的是:
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(),但又不确定该怎么做。下一步我可以尝试什么?
发布于 2020-05-11 02:33:29
您应该拆分类别,并且需要在类别数组列表中找到唯一的值。试着这样做:
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
}
]发布于 2020-05-11 16:57:01
所以感谢大家的帮助,能得到帮助真是太好了!
如果我将我的所有类别放在它们自己的数组中:
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
}
]再次感谢您的帮助:)
发布于 2020-05-11 02:28:08
尝试使用Array.filter(),不要在.map()中使用if语句
也许这会对你有所帮助:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
https://stackoverflow.com/questions/61716783
复制相似问题