js 根据某个属性值判断对象数组中的对象的该属性值相同的数组元素个数
时间: 2023-05-22 07:05:21 浏览: 185
可以使用 Array.prototype.filter 方法来过滤出符合条件的数组元素,然后获取该数组的长度即可。以下是示例代码:
```js
const arr = [
{ id: 1, name: 'A' },
{ id: 2, name: 'B' },
{ id: 3, name: 'A' },
{ id: 4, name: 'C' },
{ id: 5, name: 'A' }
];
const targetName = 'A';
const filteredArr = arr.filter(obj => obj.name === targetName);
const count = filteredArr.length;
console.log(count); // 输出结果为 3
```
注意:上述示例代码中的变量名和属性名仅供参考,实际应用中需要根据实际情况进行调整。
相关问题
js 根据属性值判断对象数组中的对象值相同的数组元素个数
可以使用 Array.prototype.filter() 和 Array.prototype.some() 方法来判断对象数组中的对象值相同的元素个数。代码示例如下:
```js
const arr = [
{ name: 'Alice', age: 20 },
{ name: 'Bob', age: 25 },
{ name: 'Alice', age: 20 },
{ name: 'Charlie', age: 30 },
{ name: 'David', age: 25 },
{ name: 'Bob', age: 25 },
]
function countDuplicates(arr, prop) {
return arr.filter((obj, index) => {
return arr.slice(index + 1).some((obj2) => {
return obj[prop] === obj2[prop]
})
}).length
}
console.log(countDuplicates(arr, 'name')) // output: 3
console.log(countDuplicates(arr, 'age')) // output: 4
```
上述代码中,使用 countDuplicates 函数来计算对象数组 arr 中,根据 prop 属性值判断相同元素的个数。该函数使用 filter() 和 some() 方法进行计算,其中 filter() 方法用于过滤掉不符合条件的元素,而 some() 方法则用于验证是否存在符合条件的元素。
JS 数组对象中某个属性值相同归类成一个数组
可以使用 Array.prototype.reduce() 方法来实现这个功能。具体步骤如下:
1. 遍历数组,对于每个元素,获取需要归类的属性值。
2. 在 reduce() 方法中创建一个对象,用于保存归类后的结果。
3. 对于每个元素,检查对象中是否已经存在该属性值对应的数组,如果不存在,则创建一个新数组,并将该元素添加到数组中;如果已经存在,则将该元素添加到对应的数组中。
4. 最后,将对象中的值转换为数组,即可得到归类后的结果。
下面是一个示例代码:
```javascript
const arr = [
{ name: 'apple', type: 'fruit' },
{ name: 'banana', type: 'fruit' },
{ name: 'carrot', type: 'vegetable' },
{ name: 'orange', type: 'fruit' },
{ name: 'broccoli', type: 'vegetable' },
{ name: 'pear', type: 'fruit' },
{ name: 'tomato', type: 'vegetable' },
{ name: 'pepper', type: 'vegetable' },
{ name: 'grape', type: 'fruit' },
{ name: 'potato', type: 'vegetable' },
];
const result = arr.reduce((obj, item) => {
if (obj[item.type]) {
obj[item.type].push(item);
} else {
obj[item.type] = [item];
}
return obj;
}, {});
console.log(result);
```
输出结果为:
```javascript
{
fruit: [
{ name: 'apple', type: 'fruit' },
{ name: 'banana', type: 'fruit' },
{ name: 'orange', type: 'fruit' },
{ name: 'pear', type: 'fruit' },
{ name: 'grape', type: 'fruit' }
],
vegetable: [
{ name: 'carrot', type: 'vegetable' },
{ name: 'broccoli', type: 'vegetable' },
{ name: 'tomato', type: 'vegetable' },
{ name: 'pepper', type: 'vegetable' },
{ name: 'potato', type: 'vegetable' }
]
}
```
在这个示例中,我们将 `arr` 数组中的元素按照 `type` 属性进行归类,得到一个包含 `fruit` 和 `vegetable` 两个属性的对象。每个属性对应一个数组,包含相同 `type` 属性值的元素。