'How to check fields in array of objects are same in javascript [duplicate]
I have an array of objects how to check all fields except two fields are same using javascript
except cid and id , check all fields are same, if so return true else false
//
var arrobj1=[
{id:1, cid:"20", name:"rsx", value: "200"},
{id:2, cid:"18", name:"rsx", value: "200", }
]
Expected Output:
true
var arrobj2=[
{id:1, cid:"20", name:"ssa", value: "200"},
{id:2, cid:"18", name:"rsx", value: "200", }
]
Expected Output:
false
var result = [...new Map(arrobj1.map(v => [v.name, v.value])).values()];
if(result.length >0){
return true;
}else{return false;}
Solution 1:[1]
You can use array.every() method:
const arrobj1 = [{
id: 1,
cid: "20",
name: "rsx",
value: "200"
},
{
id: 2,
cid: "18",
name: "rsx",
value: "200"
}
]
const arrobj2 = [{
id: 1,
cid: "20",
name: "ssa",
value: "200"
},
{
id: 2,
cid: "18",
name: "rsx",
value: "200"
}
]
const areSameObjectsArray = (objArr) => {
const firstObj = objArr[0];
const ignoredProperties = new Set(['id', 'cid']);
return objArr.every(checkObj => {
for (const key in checkObj) {
if (ignoredProperties.has(key)) continue;
if (firstObj[key] !== checkObj[key]) return false;
}
return true;
})
};
console.log(areSameObjectsArray(arrobj1));
console.log(areSameObjectsArray(arrobj2));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | EzioMercer |
