I have an array of object like this :
const object = [
{name: 'John', age: 15},
{name: 'Victor', age: 15},
{name: 'Emile', age: 14}
]
I need to check if in this array all age are 15. ( just need a boolean for answer )
I need to use something like 'every' method but how with an object ?
You need to use every:
The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value. Array.prototype.every
So the code will be like:
const object = [
{name: 'John', age: 15},
{name: 'Victor', age: 15},
{name: 'Emile', age: 14}
]
const isValid = object.every(item => item.age === 15)
console.log({isValid})
This is js functional ability to test all your elements states.
You just need to extract the property you want to compare
const object = [ {name: 'John', age: 15},{name: 'Victor', age: 15},{name: 'Emile', age: 14}]
let op = object.every(({ age }) => age === 15)
console.log(op)
You can compare the length of the array with length of array of objects with required age.
const object = [
{name: 'John', age: 15},
{name: 'Victor', age: 15},
{name: 'Emile', age: 14}
];
function hasAge(pAge, object) {
return object.length === object.filter(({ age }) => age === pAge).length;
}
console.log(hasAge(15, object));
Related
I've an array which contains the objects including various key and values. I'm going to pick out the certain values from the Array and check if the specific value is included or not in the Array.
function groupByName (contract) {
const { age } = contract;
const groups = [
{name: 'John', age: 30},
{name: 'Jack', age: 33},
{name: 'Tom', age: 40}
...
];
...
}
In order to compare the age in groups array, right now I have to use loop functions and then check one by one.
Like
groups.forEach(g => {
if (g.age === age) {
...
} else {
...
}
});
But I don't like this approach and think there are simple and effective way.
Please help me!
you can use filter to create two sublists
like this
const groups = [
{name: 'John', age: 30},
{name: 'Jack', age: 33},
{name: 'Tom', age: 40}
]
const withAge = age => groups.filter(g => g.age === age)
const withoutAge = age => groups.filter(g => g.age !== age)
const age30 = withAge(30)
const ageNot30 = withoutAge(30)
age30.forEach(g => {
console.log('do some stuff with age 30', g)
})
ageNot30.forEach(g => {
console.log('do some stuff without age 30', g)
})
maybe you can see this function
groups.some(p=>r.age===age)//if there is a object meet the criteria, return true, else return false
or read this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
by the way, if you want to execute the if/else snippet in every loop, maybe you should use forEach
Let's say I got an array of object like this
const arr = [
{name: 'John', age: 15},
{name: 'Max', age: 17},
{name: 'Tom', age: 11},
]
How can I take just the object containing Max, 17?
This would be the result
b = [{ name: Max, age: 17 }]
or better
c = { name: Max, age: 17 }
Reduce the array to the object with highest age:
const arr = [{"name":"John","age":15},{"name":"Max","age":17},{"name":"Tom","age":11}]
const result = arr.reduce((acc, o) => !acc || o.age > acc.age ? o : acc, null)
console.log(result)
I'm using null as the default value for the Array.reduce() to prevent an error if the array is empty. However, you can check for an empty array beforehand as well:
const findMaxAge = arr => arr.length
? arr.reduce((acc, o) => o.age > acc.age ? o : acc)
: null
const arr = [{"name":"John","age":15},{"name":"Max","age":17},{"name":"Tom","age":11}]
console.log(findMaxAge(arr))
console.log(findMaxAge([]))
You can sort by age first, then the object with the highest age value will be at the start of the list:
const a = [
{name: "John", age: 15},
{name: "Max", age: 17},
{name: "Tom", age: 11},
]
const sortedByAge = a.sort((a,b) => b.age - a.age);
const highestAge = sortedByAge[0];
console.log(highestAge);
hope this code helping you
const a = [{name: 'John', age: 15},
{name: 'Max', age: 17},
{name: 'Tom', age: 11},];
const result = a.reduce((p, c) => p.age > c.age ? p : c);
console.log(result);
Using the Array.prototype.reduce() is a clean way.
this function iterates through the array one by one, at each step adding the current array value to the result from the previous step. in our case will compare the previous largest element to the current. the return value will be the object containing the largest value for the age key.
const arr = [
{name: 'John', age: 15},
{name: 'Max', age: 17},
{name: 'Tom', age: 11},
]
const largest = arr.reduce((prev, current) => (prev.age > current.age) ? prev : current)
console.log(largest);
I have a javascript object as follows.
{
name: "tom",
age: 5,
fruits: [
{name: "apple",qty: 4},
{name: "orange",qty: 13},
{name: "banana",qty: 3}
]
}
I am trying to convert this object into an object given below.
{
name: "tom",
age: 5,
apple: 4,
orange: 13,
banana: 3
}
How do I achieve this? I have tried to loop through the fruits array but I am unable to find a way to create a variable with the fruit name and assign the qty to it.
You can use forEach and delete to clean up the old key. Take care not to overwrite keys accidentally, though (you could test if (e.name in obj) as a safety check).
const obj = {
name: "tom",
age: 5,
fruits: [
{name: "apple",qty: 4},
{name: "orange",qty: 13},
{name: "banana",qty: 3}
]
};
obj.fruits.forEach(e => obj[e.name] = e.qty);
delete obj.fruits;
console.log(obj);
you can use below simple code
var b={
name: "tom",
age: 5}
for (var i = 0; i<a.fruits.length; i++) {
b[a.fruits[i].name]=a.fruits[i].qty;
}
This a generic function to convert if you don't want to mutate the original object. Destructure the object to get fruits and rest of the properties separately. Then you can use Object.assign() and map to to create a new object.
let obj = {
name: "tom",
age: 5,
fruits: [
{name: "apple",qty: 4},
{name: "orange",qty: 13},
{name: "banana",qty: 3}
]
}
const converter = ({ fruits, ...rest }) =>
Object.assign(rest, ...fruits.map(({ name, qty }) => ({ [name]: qty })))
console.log(converter(obj))
I have an array of objects and trying to take thevalues inside those objects and push them into an array based on the same property value. So for example.
array = [
{name: 'John', age: 12},
{name: 'Lily', age: 22}
]
I have this array of objects and now I want to iterate through it and create arrays with all name values and age values. The array also needs to be the same name as the values. So the result will be.
name = ['John', 'Lily']
age = [12, 22]
How would I be able to do this?
Just map over the array like so:
const array = [
{name: 'John', age: 12},
{name: 'Lily', age: 22}
]
const name = array.map(e => e.name);
const age = array.map(e => e.age);
console.log(name);
console.log(age);
EDIT
If the array has dynamic objects, you can do this:
const array = [
{name: 'John', age: 12},
{name: 'Lily', age: 22}
];
for (var key in array[0]) {
window[key] = array.map(e => e[key]);
}
console.log(name);
console.log(age);
Lets Suppose I have 1000's of objects. Now I want to store objects with same name in an array So that I'll have multiple arrays having objects with same name. How can this be done in JavaScript?
Data can be like this
var input = [
{ name: 'ABC', age: 12 },
{ name: 'XYZ', age: 13 },
{ name: 'ABC', age: 14 },
{ name: 'XYZ', age: 15 },
];
var output = {};
input.forEach(function(obj) {
var array = output[obj.name];
if (!array) {
array = output[obj.name] = [];
}
array.push(obj)
})
for(name in output) {
console.log('There are ' + output[name].length + ' people named ' + name);
}
In javascript, objects aren't copied into arrays. They exist in memory and when added to a an array the reference to that object is what lives in an array.
In the following code, myObj === arr1[0] === arr2. Which means the following is true:
var myObj = {name:'Dave', age: 55};
var arr1 = [myObj];
var arr2 = [myObj];
arr2[0].age = 44;
console.log(myObj.age);
// prints 44
console.log(arr1[0].age);
// prints 44
So to get what you need, you just need to organize your data into arrays. In javascript, you can filter arrays:
// original data
var data = [
{name: 'ABC', age: 12},
{name: 'XYZ', age: 13},
{name: 'ABC', age: 14},
{name: 'XYZ', age: 15},
{name: 'XYZ', age: 16},
];
// this returns a function to be used in Array.filter to filter for objects with the specified name
function nameFilter(name) {
return function(datum) {
return datum.name === name;
}
}
// filter for each type
var abcPeople = data.filter(nameFilter('ABC'));
var xyzPeople = data.filter(nameFilter('XYZ'));
console.log(data.length);
//5
console.log(abcPeople.length);
//2
console.log(xyzPeople.length);
//3
If you run the above code, you would have 3 arrays and all object in abcPeople would also be in data such that any change to one would be reflected in the other. The same is true for xyzPeople. Just to be clear, filter creates a new array, so data is not modified.
UPDATE: Added example where lists are dynamically determined
// original data
var data = [
{name: 'ABC', age: 12},
{name: 'XYZ', age: 13},
{name: 'ABC', age: 14},
{name: 'XYZ', age: 15},
{name: 'XYZ', age: 16},
];
var sortedData = {};
data.forEach(function(datum){
// initializes an array for any unseen name
if(!sortedData[datum.name]) {
sortedData[datum.name] = [];
}
// add the datum to the list for its name
sortedData[datum.name].push(datum);
});
// all names
console.log(Object.keys(sortedData));
// "ABC", "XYZ"
// items named "ABC"
console.log(sortedData['ABC']);
// [{"name": "ABC","age": 12}, {"name": "ABC","age": 14}]