我有两个数组
array1 = [
{name: "samsung", views: 1200},
{name: "apple", views: 200}
]
array2 = [
{name: "samsung-1234", views: 200},
{name: "apple-2332", views: 200},
{name: "samsung-6543", views: 400},
{name: "samsung-9876", views: 600}
]
在array2中,如何获取sumsung
有3种类型,apple
具有1
类型。
谢谢。感谢您的帮助
答案 0 :(得分:3)
您可以在array2
上使用.filter()
并从name
中指定array1
来建立过滤器,并用.includes()
来比较名称
let array1 = [
{name: "samsung", views: 1200},
{name: "apple", views: 200}
];
let array2 = [
{name: "samsung-1234", views: 200},
{name: "apple-2332", views: 200},
{name: "samsung-6543", views: 400},
{name: "samsung-9876", views: 600}
];
let result = array1.map(x => ({ name: x.name, total: array2.filter(a => a.name.includes(x.name)).length }));
console.log(result);
答案 1 :(得分:1)
您可以拍摄一张地图以统计发生次数并更新array1
。
var array1 = [{ name: "samsung", views: 1200 }, { name: "apple", views: 200 }],
array2 = [{ name: "samsung-1234", views: 200 }, { name: "apple-2332", views: 200 }, { name: "samsung-6543", views: 400 }, { name: "samsung-9876", views: 600 }];
types = new Map(array1.map(o => ([o.name, Object.assign(o, { types: 0 })])));
array2.forEach(({ name }) => ++types.get(name.split('-')[0]).types);
console.log(array1);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 2 :(得分:0)
array1.map(el => {
return array2.filter(el2 => {
return el2.name.includes(el.name)
})
})
对您有帮助吗?
答案 3 :(得分:0)
我不确定我是否了解第一个数组的含义,但是可以通过简单的for循环使用Samsung获得项目数。
let cnt = 0;
array2.forEach((val) => {if (val.name.match(/samsung/i)) { cnt++}})
console.log(cnt) // 3
答案 4 :(得分:0)
array1 = [
{name: "samsung", views: 1200},
{name: "apple", views: 200}
]
array2 = [
{name: "samsung-1234", views: 200},
{name: "apple-2332", views: 200},
{name: "samsung-6543", views: 400},
{name: "samsung-9876", views: 600}
]
const result = array1.map(brand => {
let howManyTypes = array2.filter(ele => ele.name.indexOf(brand.name) != -1).length;
return {name: brand.name, howManyTypes}
})
console.log(result)