Related
I have the following data structure:
persons: [
{ name: 'Joe', age: 20 },
{ name: 'Alex', age: 24 },
{ name: 'Joe', age: 34 },
{ name: 'Bob', age: 19 },
{ name: 'Alex', age: 56 },
]
I want to get the oldest person-object for each existing name. So the result of this example would be:
filteredPersons: [
{ name: 'Joe', age: 34 },
{ name: 'Bob', age: 19 },
{ name: 'Alex', age: 56 },
]
How can I achieve this? Note that the number of different names is not fixed.
You could take a Map and collect older ages for same names.
This soultion feature a function which compares two objects (or one object and a possible undefined) and if truthy and b.age is greater then a.age, it returns b, otherwise a.
At the end, only the values of the map are taken as result set.
const
older = (a, b) => b?.age > a.age ? b : a,
persons = [{ name: 'Joe', age: 20 }, { name: 'Alex', age: 24 }, { name: 'Joe', age: 34 }, { name: 'Bob', age: 19 }, { name: 'Alex', age: 56 }],
result = Array.from(persons.reduce((m, o) => m.set(
o.name,
older(o, m.get(o.name))
), new Map).values());
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
To do that in a single pass, you may employ Array.prototype.reduce() building up the Map that will have name as a key and store maximum age together with name as a value-object.
Once the Map is ready, you may extract its values with Map.prototype.values():
const src = [{name:'Joe',age:20},{name:'Alex',age:24},{name:'Joe',age:34},{name:'Bob',age:19},{name:'Alex',age:56},],
result = [...src
.reduce((acc, {name, age}) => {
const match = acc.get(name)
match ?
match.age = Math.max(age, match.age) :
acc.set(name, {name,age})
return acc
}, new Map)
.values()
]
console.log(result)
.as-console-wrapper{min-height:100%;}
Simply reduce the array and for each person in the array, check if the item has been encountered before, if so keep the oldest one, otherwise just keep the current object:
let results = persons.reduce((acc, person) => { // for each person in persons
if(!acc[person.name] || acc[person.name].age < person.age) { // if this person has never been encountered before (acc[person.name]) or if the already encountered one is younger (acc[person.name].age < person.age)
acc[person.name] = person; // store the current person under the name
}
return acc;
}, Object.create(null)); // Object.create(null) instead of {} to create a prototypeless object
This will return an object containing the oldest persons in this format { name: person, name: person, ... }. If you want to get them as an array, call Object.values like so:
let arrayResults = Object.values(results);
Demo:
let persons = [{ name: 'Joe', age: 20 }, { name: 'Alex', age: 24 }, { name: 'Joe', age: 34 }, { name: 'Bob', age: 19 }, { name: 'Alex', age: 56 }];
let results = persons.reduce((acc, person) => {
if(!acc[person.name] || acc[person.name].age < person.age) {
acc[person.name] = person;
}
return acc;
}, Object.create(null));
let arrayResults = Object.values(results);
console.log("results:", results);
console.log("arrayResults:", arrayResults);
Hope this is more understandable for you.
const persons = [
{ name: 'Joe', age: 20 },
{ name: 'Alex', age: 24 },
{ name: 'Joe', age: 34 },
{ name: 'Bob', age: 19 },
{ name: 'Alex', age: 56 },
]
let personsObj = {}, mxPersons = []
persons.forEach(person => {
if (personsObj[person.name] == undefined) {
personsObj[person.name] = person.age
} else {
personsObj[person.name] = Math.max(person.age, personsObj[person.name])
}
})
for (const [key, value] of Object.entries(personsObj)) {
mxPersons.push({
name: key,
age: value
})
}
console.log(mxPersons)
The oldest people per name can be obtained by first grouping all people based on their name, then take the oldest person of each group.
This answer does introduce two helper functions groupBy and maxBy, which add some overhead but are really usefull in general.
const people = [
{ name: 'Joe', age: 20 },
{ name: 'Alex', age: 24 },
{ name: 'Joe', age: 34 },
{ name: 'Bob', age: 19 },
{ name: 'Alex', age: 56 },
];
const oldestPeople = Array
.from(groupBy(people, person => person.name).values())
.map(people => maxBy(people, person => person.age));
console.log(oldestPeople);
function groupBy(iterable, fn) {
const groups = new Map();
for (const item of iterable) {
const key = fn(item);
if (!groups.has(key)) groups.set(key, []);
groups.get(key).push(item);
}
return groups;
}
function maxBy(iterable, fn) {
let max, maxValue;
for (const item of iterable) {
const itemValue = fn(item);
if (itemValue <= maxValue) continue;
[max, maxValue] = [item, itemValue];
}
return max;
}
How to sort and get max score for each name from 3 array of objects in javascript and assign it and the missing keys and values to another array?
I want to sort the arrays test1, test2, test3 and get the max score for each student and assign it and the missing keys and values to the array results as an object like:
results = [{name: name, age: age score: score}]
With the following code I am able to get the object with the highest score like:
resutls = [
{ name: 'sam', age: 15, score: 30 }
]
const test1 = [
{ name: 'vikash', score: 1 },
{ name: 'krish', score: 2 },
{ name: 'kunz', score: 3 },
];
const test2 = [
{ name: 'kunz', score: 0 },
{ name: 'vikash', score: 5 },
{ name: 'krish', score: 6 },
{ name: 'sam', age: 15, score: 30 },
];
const test3 = [
{ name: 'krish', score: 7 },
{ name: 'kunz', age: 10, score: 8 },
{ name: 'vikash', score: 10 },
{ name: 'sam', score: '' },
];
const topScore = (...arrays) => {
let result = [...arrays].flat().reduce((max, obj) => {
return max.score < obj.score ? obj : max;
});
return [result];
};
console.log(topScore(test1, test2, test3));
The results array should look like this at the end of it ..
resutls = [
{ name: 'vikash', age: '', score: 10 },
{ name: 'sam', age: 15, score: 30 },
{ name: 'krish', age: '', score: 7 },
{ name: 'kunz', age: 10, score: 8 },
]
You could group by name and get all values from the object with the max score objects.
const
test1 = [{ name: 'vikash', score: 1 }, { name: 'krish', score: 2 }, { name: 'kunz', score: 3 }],
test2 = [{ name: 'kunz', score: 0 }, { name: 'vikash', score: 5 }, { name: 'krish', score: 6 }, { name: 'sam', age: 15, score: 30 }],
test3 = [{ name: 'krish', score: 7 }, { name: 'kunz', age: 10, score: 8 }, { name: 'vikash', score: 10 }, { name: 'sam', score: '' }],
result = Object.values([...test1, ...test2, ...test3].reduce((r, o) => {
if (!r[o.name] || r[o.name].score < o.score) {
r[o.name] = { ...(r[o.name] || { name: '', age: '', score: 0 }), ...o };
}
return r;
}, {}));
console.log(result);
You just select the maximum of all the results, to get an array you can build a dictionary of result by name and then select all the maximums:
const test1 = [
{ name: 'vikash', score: 1 },
{ name: 'krish', score: 2 },
{ name: 'kunz', score: 3 },
];
const test2 = [
{ name: 'kunz', score: 0 },
{ name: 'vikash', score: 5 },
{ name: 'krish', score: 6 },
{ name: 'sam', age: 15, score: 30 },
];
const test3 = [
{ name: 'krish', score: 7 },
{ name: 'kunz', age: 10, score: 8 },
{ name: 'vikash', score: 10 },
{ name: 'sam', score: '' },
];
const topScore = (...arrays) => {
let result = [...arrays].flat().reduce((max, obj) => {
//check if current item or maximum item contains an age.
let age = obj.age || (max[obj.name] || {age: ''}).age
return (max[obj.name] || {score: 0}).score < obj.score ? {...max,[obj.name]: {...obj , age}} : {...max }
}, {});
return Object.values(result)
};
console.log(topScore(test1, test2, test3));
so i'm doing some excercises as practice, since i'm a beginner, and i stumble into this problem that i can't solve, would anybody be kind to give me a hand?
i would like to make a function that returns how many people is 18 or older, this is what i've been trying but i'm a bit confused..
const examplePeople = [
{ name: 'John', age: 15 },
{ name: 'Jane', age: 16 },
{ name: 'Jack', age: 25 },
{ name: 'Ana', age: 18 },
{ name: 'Raul', age: 23 },
{ name: 'Pedro', age: 17 }
];
function countLegalPeople(people) {
for (i= 0; i >= people["age"] ; i++){
if (people[i]["age"] >= 18) {
return people[i];
}
}
}
console.log(countLegalPeople(examplePeople));
Why don't try Array.prototype.filter()
const examplePeople = [
{ name: 'John', age: 15 },
{ name: 'Jane', age: 16 },
{ name: 'Jack', age: 25 },
{ name: 'Ana', age: 18 },
{ name: 'Raul', age: 23 },
{ name: 'Pedro', age: 17 }
];
function countLegalPeople(people) {
return people.filter(p => p.age >= 18).length;
}
console.log(countLegalPeople(examplePeople));
I'd use reduce, where the accumulator is the number of objects found so far that pass the test:
const examplePeople = [
{ name: 'John', age: 15 },
{ name: 'Jane', age: 16 },
{ name: 'Jack', age: 25 },
{ name: 'Ana', age: 18 },
{ name: 'Raul', age: 23 },
{ name: 'Pedro', age: 17 }
];
const result = examplePeople.reduce((a, { age }) => a + (age >= 18), 0);
console.log(result);
With a for loop, you'd have to increment a more persistent variable, eg
const examplePeople = [
{ name: 'John', age: 15 },
{ name: 'Jane', age: 16 },
{ name: 'Jack', age: 25 },
{ name: 'Ana', age: 18 },
{ name: 'Raul', age: 23 },
{ name: 'Pedro', age: 17 }
];
let result = 0;
for (let i = 0; i < examplePeople.length; i++) {
if (examplePeople[i].age >= 18) {
result++;
}
}
console.log(result);
But array methods are generally more terse and elegant IMO.
The issue with your approach is that you are returning within your for loop. Whenever you return, your function will stop running (it essentially jumps out of your function), so, whenever you run into a person over the age of 18 you stop your loop and thus it cannot count any more people.
Instead, you can create a variable and set it to zero. This will count how many people of the age of 18 you have seen. To do this, you will need to add one to this variable each time you see a person of an age of 18 or higher. Then, once your for loop is complete, you can return this number.
See example below:
const examplePeople = [
{ name: 'John', age: 15 },
{ name: 'Jane', age: 16 },
{ name: 'Jack', age: 25 },
{ name: 'Ana', age: 18 },
{ name: 'Raul', age: 23 },
{ name: 'Pedro', age: 17 }
];
function countLegalPeople(people) {
let counter = 0; // number of people >= 18;
for (let i= 0; i < people.length; i++){ // loop through the array of people (using people.length)
if (people[i]["age"] >= 18) {
counter++; // age 1 to counter (same as counter = counter + 1)
}
}
return counter; // return the amount of people >= 18
}
console.log(countLegalPeople(examplePeople));
Your question was slightly confusing and could be taken two different ways, so if you are looking to return the total instances of people that are 18 and older in a new array, you would do something like this:
const examplePeople = [
{ name: 'John', age: 15 },
{ name: 'Jane', age: 16 },
{ name: 'Jack', age: 25 },
{ name: 'Ana', age: 18 },
{ name: 'Raul', age: 23 },
{ name: 'Pedro', age: 17 }
];
let adults = [];
for (let i = 0; i < examplePeople.length; i++) {
if (examplePeople[i].age >= 18) {
adults.push(examplePeople[i]);
}
}
console.log(adults);
you can also get the length with a simple:
console.log(adults.length);
I have an object of students & I'd like to get the name of the youngest student.
const students = [
{ name: 'Hans', age: 3 },
{ name: 'Ani', age: 7 },
{ name: 'Budi', age: 10 },
{ name: 'Lee', age: 13 }
]
I get the youngest age by this
function getYoungestAge(data) {
return resultMin = data.reduce((min, p) => p.age < min ? p.age : min, data[0].age)
}
getYoungestAge(students) // return 3
How can I return not only age but also name ? // example: 3 and Hans
You can always take the whole object through your reduce and not just the age
const students = [
{ name: 'Hans', age: 3 },
{ name: 'Ani', age: 7 },
{ name: 'Budi', age: 10 },
{ name: 'Lee', age: 13 }
]
function getYoungestAge(data) {
return data.reduce((min, p) => p.age < min.age ? p : min, data[0])
}
var youngest = getYoungestAge(students)
console.log(youngest);
Another way would be to sort the list and take the first. NOTE: This way changes the original array. That is fine in some cases and undesirable in others. I prefer the first way above in most cases.
const students = [
{ name: 'Hans', age: 3 },
{ name: 'Ani', age: 7 },
{ name: 'Budi', age: 10 },
{ name: 'Lee', age: 13 }
]
function getYoungestAge(data) {
data.sort( (x,y) => x.age-y.age);
return data[0];
}
var youngest = getYoungestAge(students)
console.log(youngest);
Also note that both of these solutions return the first item with the lowest age where more than 1 student shares the same age.
You could return an array with the filtered objects. This works with a single loop and if some people have the same mininmum age, then all peoples with that age are returned.
function getYoungestAge(data) {
return data.reduce(function (r, o, i) {
if (!i || o.age < r[0].age) {
return [o];
}
if (o.age === r[0].age) {
r.push(o)
}
return r;
}, []);
}
const students = [{ name: 'Hans', age: 3 }, { name: 'Ani', age: 7 }, { name: 'Budi', age: 10 }, { name: 'Lee', age: 13 }]
console.log(getYoungestAge(students));
Reduce the array to a Map, with the age as key, and the value an array of all the students with that age. To get the youngest, find the min of the the map's keys, and get the value of that key from the map:
const students = [{"name":"Hans","age":3},{"name":"Ani","age":7},{"name":"Morgan","age":3},{"name":"Budi","age":10},{"name":"Lee","age":13}]
const studentsByAgeMap = students.reduce((m, o) => {
m.has(o.age) || m.set(o.age, [])
m.get(o.age).push(o)
return m
}, new Map())
const result = studentsByAgeMap.get(Math.min(...studentsByAgeMap.keys()))
console.log(result)
Using Lodash the above can be achieved in one line.
_.minBy(students, function(o) {return o.age})
I have two arrays that I would like to compare and provide a count of the items in the master list.
The master list might look like this:
{ name: 'Jon', age: 34 },
{ name: 'Steve', age: 33 },
{ name: 'Mark', age: 34 },
{ name: 'Jon', age: 35 }
The Filter list gets all possible names / ages from the database. Some might not have any entries. Each of these lists are getting pulled from an API individually. I will combine them into one array:
{ users:
[{ username: 'Jon' },
{ userName: 'Steve' },
{ username: 'Mark' },
{ username: 'Mike' }],
ages:
[{age: 33},
{age: 34},
{age: 35},
{age: 36}]
}
What I would like to do is be able to count how many of each name I have
Jon - 2, Steve - 1, Mark - 1, Mike - 0
33 - 1, 34 - 2, 35 - 1
Here is a generic approach. You provide the data and the field you want to count.
var data = [
{ name: 'Jon', age: 34 },
{ name: 'Steve', age: 33 },
{ name: 'Mark', age: 34 },
{ name: 'Jon', age: 35 }
];
function countUnique(items, property) {
return items.reduce(function(map, item) {
if (item.hasOwnProperty(property)) {
map[item[property]] = (map[item[property]] || 0) + 1;
}
return map;
}, {});
}
console.log(countUnique(data, 'name')); // Object {Jon: 2, Steve: 1, Mark: 1}
console.log(countUnique(data, 'age')); // Object {33: 1, 34: 2, 35: 1}
Filtering
If you want to filter a list of users by conditions, you can define an array of filter objects as seen below. When filtering a list of items, you usually will provide a predicate function to execute on the current item in the filter call. This function returns a boolean value which determines whether or not the item meets the conditions of the function.
var users = [
{ name: 'Jon', age: 34 },
{ name: 'Steve', age: 33 },
{ name: 'Mark', age: 34 },
{ name: 'Jon', age: 35 }
];
var filters = [{
name: 'users',
predicate : function(user) {
return [ 'Jon', 'Mark', 'Mike' ].indexOf(user.name) > -1;
}
}, {
name: 'ages',
predicate : function(user) {
return user.age >= 34 && user.age <= 36;
}
}];
print(filterFactory(users, getFiltersByName(filters, ['users', 'ages'])));
function getFiltersByName(filters, names) {
return filters.filter(function(filter) {
return names.indexOf(filter.name) > -1;
});
}
function filterFactory(items, filters) {
return items.filter(function(item) {
return filters.some(function(filter) {
try { return filter.predicate.call(undefined, item); }
catch (e) { throw new Error('predicate undefined for filter: ' + filter.name); }
});
});
}
function print(obj) {
document.body.innerHTML = JSON.stringify(obj, undefined, ' ');
}
body { font-family: monospace; white-space: pre }
Something like this would do. Here is a fiddle http://jsfiddle.net/5jkqv6k3/
var data = [
{ name: 'Jon', age: 34 },
{ name: 'Steve', age: 33 },
{ name: 'Mark', age: 34 },
{ name: 'Jon', age: 35 }
];
var key = function(obj) {
// Some unique object-dependent key
return obj.name; // Just an example
};
var dict = {};
for (var i = 0; i < data.length; i++) {
if (dict[key(data[i])])
dict[key(data[i])] = dict[key(data[i])] + 1;
else
dict[key(data[i])] = 1;
}
console.log(dict);
Using angularJs (because you're using it as you said) you can do this:
var countNamesList = {};
var countAgesList = {};
angular.forEach(masterList, function(value, index) {
countNamesList[masterList[index].name] =
(!angular.isUndefined(countNamesList[masterList[index].name])) ?
countNamesList[masterList[index].name] + 1 : 1;
countAgesList[masterList[index].age] =
(!angular.isUndefined(countAgesList[masterList[index].age])) ?
countAgesList[masterList[index].age] + 1 : 1;
});
console.log(countNamesList);
console.log(countAgesList);
JSFIDDLE
Mr. Polywhirl's answer is your best option on counting.
Now here's how you can filter:
var master = [
{ name: 'Jon', age: 34 },
{ name: 'Steve', age: 33 },
{ name: 'Mark', age: 34 },
{ name: 'Jon', age: 35 }
];
var filter = {
users: [
{ username: 'Jon' },
{ username: 'Mark' },
{ username: 'Mike' }
], ages: [
{ age: 34 },
{ age: 35 },
{ age: 36 }
]
};
function filterByNameAndAge(obj) {
return filter.users.some(function(user) {
return user.username === obj.name;
}) && filter.ages.some(function(age) {
return age.age === obj.age;
});
}
console.log(master.filter(filterByNameAndAge));
Currently it accepts only objects with matching name and age. Replace the && inside filterByNameAndAge by || if it should accept objects with matching name or age.