I need to check if each value of a specific key in an object array are equal or null.
So far I have got this method
const allEqual = (arr, key) =>
arr.every((v) => v[key] === arr[0][key] || v[key] === null);
Which takes in a array and key and checks if the key matches based on Array.prototype.every().
Whilst this works great if there are no null values, when there is a null value it doesn't.
const allEqual = (arr, key) =>
arr.every((v) => v[key] === arr[0][key] || v[key] === null);
let example1 = [
{
test: "foo",
},
{
test: "foo",
},
{
test: "foo",
},
];
//This works
console.log(allEqual(example1, "test"));
let example2 = [
{
test: null,
},
{
test: "foo",
},
{
test: "foo",
},
];
//This DOES Not work
console.log(allEqual(example2, "test"));
//This works
let example3 = [
{
test: "foo",
},
{
test: "foo",
},
{
test: null,
},
];
console.log(allEqual(example3, "test"));