Check if objects in array contain equal properties - javascript

I have an array of objects, each with various properties. I want to check if one particular property is equal across all of the objects. e.g.
peopleArr = [
{
name: Simon,
age: 22,
hair: brown
},
{
name: John,
age: 22,
hair: black
},
{
name: James,
age: 22,
hair: blond
}
]
I need a function that returns true if age has the same value across all of the objects in the array, and false if not. I've tried some variations using .every, but can't get it to work with object properties specifically (I'm relatively new). Any help appreciated.

You can use array every method and inside the callback check if age in all the object is equal to 22. It will return Boolean value and it will return true if all all the object matches the condition
const peopleArr = [{
name: 'Simon',
age: 22,
hair: 'brown'
},
{
name: 'John',
age: 22,
hair: 'black'
},
{
name: 'James',
age: 23,
hair: 'blond'
}
]
const res = peopleArr.every(item => item.age === 22);
console.log(res)

An alternative to using the .every() method, would be to filter the array and compare the filtered array length to the original array length. Like so
const peopleArr = [
{
name: "Simon",
age: 22,
hair: "brown"
},
{
name: "John",
age: 22,
hair: "black"
},
{
name: "James",
age: 22,
hair: "blond"
}
]
const array_val_same = ( arr, val ) => {
let filtered = arr.filter(el => el.age === val)
return filtered.length === arr.length ? true : false
}
array_val_same(peopleArr, 22)
This is just an alternative, i'd still use .every() though.

Related

Map object property only when it is defined (not null) [duplicate]

This question already has answers here:
In JavaScript, how to conditionally add a member to an object?
(29 answers)
Add property to object when it's not null
(3 answers)
Closed 1 year ago.
Let’s consider the next array:
const arr = [
{
name: "bob",
age: 25,
salary: 1000
},
{
name: "bill",
age: 32,
salary: 1500
},
{
name: "jake",
age: 16,
salary: null
},
]
I need to map every object to be the next structure:
firstName: string;
personAge: string;
grossSalary?: number;
so
const mappedArr = arr.map(person => ({
firstName: person.name,
personAge: person.age,
...{grossSalary:
person.salary
? person.salary
: // I'm stuck :'((
}
}))
I need to map person.salary only if it’s not null in the original object. Otherwise, I need to omit it.
I believe I’m pretty close with the spread operator but I guess I need a ternary to return an empty object if the salary is null in the original object. Maybe this approach is wrong... idk anymore...
You can check the salary based on which you can return the object:
const arr = [
{
name: "bob",
age: 25,
salary: 1000
},
{
name: "bill",
age: 32,
salary: 1500
},
{
name: "jake",
age: 16,
salary: null
},
]
const mappedArr = arr.map(person => (
person.salary
? { firstName: person.name, personAge: person.age, grossSalary: person.salary }
: { firstName: person.name, personAge: person.age }
)
);
console.log(mappedArr);

javascript : compare content of two array of objects by some id and return true or false

i need a little help to compare two array of objects and look if the array A has the same content of array B by using an id who is inside both arrays, for example:
example false:
ArrayObjectA = [{
id: 1,
name: josh,
age: 31
},{
id: 2,
name: Kyle,
age: 21}];
ArrayObjectB = [{
id: 1,
name: josh,
age: 31
}];
ArrayObjectB content is equals to ArrayObjectA => false
example true:
ArrayObjectA = [{
id: 1,
name: josh,
age: 31
},{
id: 2,
name: Kyle,
age: 21}];
ArrayObjectB = [{
id: 1,
name: josh,
age: 31
},{
id: 2,
name: Kyle,
age: 21}];
ArrayObjectB content is equals to ArrayObjectA => true
i found a library called lodash but i dont know if is useful.
any help is appreciated.
We can get ids list from each array and check if all elements are equal
const compareArrays = (arr1, arr2) => {
const ids1 = arr1.map(v => v.id).sort()
const ids2 = arr2.map(v => v.id).sort()
return ids1.length === ids2.length && ids1.every((v, ind) => v === ids2[ind])
}

How to check the depth of every object field in Javascript

I have a navigation function in my React Native app, that outputs to the console all the arguments passed to it in the developer's mode, and sometimes i sent a big store to the arguments and it can not be output. Get the error about the cyclic object reference, because the object is very deep. Therefore I decided to create a function that will check all the fields of the object and depends on it will output the information to the console, for example if the object filed is deeper than 1 level.
const notDeepObj = {
name: 'John',
surname: 'Robert',
age: 28,
family: false,
};
const deepObj = {
name: 'John',
surname: 'Robert',
bankAccount: {
accounts: 2,
cash: true,
credit false,
wasCreated: {
city: 'New-York',
date: '12.02.2020.',
}
}
}
function checkDepthOfObject(obj){}
In the case of not deep object it has to return the object itself like this:
checkDepthOfObject(notDeepObj)
//it will return:
{
name: 'John',
surname: 'Robert',
age: 28,
family: false,
};
And in the case of the deep object it has to return all not deep fields and plus the flag for the deep field of the object:
checkDepthOfObject(notDeepObj)
//it will return:
{
name: 'John',
surname: 'Robert',
bankAccount: '[DEEP_OBJECT]'
};
Can you recommend me please the best way how can I do it.
Use Object.entries and map and check for typeof value.
const notDeepObj = {
name: "John",
surname: "Robert",
age: 28,
family: false
};
const deepObj = {
name: "John",
surname: "Robert",
bankAccount: {
accounts: 2,
cash: true,
credit: false,
wasCreated: {
city: "New-York",
date: "12.02.2020."
}
}
};
function checkDepthOfObject(obj) {
return Object.fromEntries(
Object.entries(obj).map(([key, value]) => [
key,
typeof value === "object" ? "[DEEP_OBJECT]" : value
])
);
}
console.log(checkDepthOfObject(notDeepObj));
console.log(checkDepthOfObject(deepObj));

Filter a javascript array by an object only containing a subset of the array properties

I have an array of objects that have many properties. I would like to be able to find the matching items, based on a filter object that only contains a subset of the arrays properties. For Example, i have a customer
let Customer = {
Name: "John Doe",
Age: 80,
Hair: "Red",
Gender: "Male",
};
And i have my search object:
let searchObject ={
Hair: "Red",
Gender: "Male"
}
I want to be able to find inside my array, all customers that match searchObject, without having to do:
this.array.filter(z=>z.Hair == searchObject.Hair && z.Gender == searchObject.Gender);
I would like for it to be when searchObject adds more properties, it automatically filters on those too
You can use every() on Object.keys() of searchObject inside and check if all the values of keys in searchObject matches with corresponding values of object in array.
Below in the snippet I have two object with different Gender
let array = [{
Name: "John Doe",
Age: 80,
Hair: "Red",
Gender: "Male",
},{
Name: "Marry",
Age: 80,
Hair: "Red",
Gender: "Female",
}]
let searchObject ={
Hair: "Red",
Gender: "Male"
}
const res = array.filter(x => Object.keys(searchObject).every(k => x[k] === searchObject[k]));
console.log(res)
You could take the entries and filter by the key/value pairs.
var customers = [{ Name: "John Doe", Age: 80, Hair: "Red", Gender: "Male" }],
searchObject = { Hair: "Red", Gender: "Male" },
search = Object.entries(searchObject),
result = customers.filter(o => search.every(([k, v]) => o[k] === v));
console.log(result);

Filter an array of objects returns empty array

I hae the following array of objects:
arr = [
{
name: "john",
age: 24,
gender: "male"
},
{
name: "jane",
age: 27,
gender: "female"
},
{
name: "joe",
age: 29,
gender: "male"
}
]
I'm trying to filter the name and age property into a new array. I tried this:
const newFields = arr.filter((item) => {
return (
item.name && item.age
);
});
But for some reason newFields returns an empty array.
Instead of .filter() use .map()
const arr = [
{
name: "john",
age: 24,
gender: "male"
},
{
name: "jane",
age: 27,
gender: "female"
},
{
name: "joe",
age: 29,
gender: "male"
}
];
const newFields = arr.map(item => {
return {
name: item.name,
age: item.age
}
});
console.log(newFields)
This can be a one liner too with the arrow function and Parameter Context Matching
const newFields = arr.map(({ name, age }) => ({ name, age }));
Your solution's result can not be empty but the original array, because in this case the return value of your filter function will be always true (every item has the name and age property) which doesn't filter anything from the original arr variable.
If you are creating a new array with a subset of the original - then you can iterate over the array and push the desired elements into its own array.
That said if all you are trying to get is the name and age of the existing array - why do you need to create a separate array? - you can just iterate over the original array and reference only the desired values from each item.
let arr = [
{
name: "john",
age: 24,
gender: "male"
},
{
name: "jane",
age: 27,
gender: "female"
},
{
name: "joe",
age: 29,
gender: "male"
}
]
let newArr = [];
arr.forEach(function(item) {
newArr.push({name:item.name, age:item.age})
});
console.log(newArr); // gives [{"name": "john","age": 24},{"name": "jane","age": 27},{"name": "joe","age": 29}]

Categories