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.
Related
I can't do this thing. I would like the parameter inserted in the function to return that specific value of the object to me.
If I insert "over" I would like an array with the names whose age is over 50, while on the contrary if I insert under, it doesn't work!
const person = [
{ name: 'Jessica', age: 25 },
{ name: 'Ilary', age: 27 },
{ name: 'Frank', age: 70 },
{ name: 'Dan', age: 65 },
{ name: 'Pop', age: 22 },
{ name: 'Maur', age: 68 },
];
let nameOver50 = [];
let nameUnder50 = [];
function check(enter) {
person.filter(({ name, age }) => {
if (age > 50 && enter === 'over') {
nameOver50.push({ name });
} else if (age < 50 && enter === 'under') {
nameUnder50.push(name);
}
});
console.log(nameUnder50);
}
check('over');
thank you in advance!
From what I understand, if you want it to return as an array of names, then you should return the name only, which is as a string, instead of returning the name object.
const person = [
{ name: 'Jessica', age: 25 },
{ name: 'Ilary', age: 27 },
{ name: 'Frank', age: 70 },
{ name: 'Dan', age: 65 },
{ name: 'Pop', age: 22 },
{ name: 'Maur', age: 68 },
];
let nameOver50 = [];
let nameUnder50 = [];
function check(enter) {
enter === 'over'
? (nameOver50 = person
.filter(({ name, age }) => age > 50)
.map(({ name }) => name))
: (nameUnder50 = person
.filter(({ name, age }) => age < 50)
.map(({ name }) => name));
}
check('over');
check('under');
console.log(nameOver50);
console.log(nameUnder50);
It looks like you're only logging nameUnder50 yet you are passing 'over' to the function
nameOver50 is the array you should be logging or both:
const person = [
{ name: 'Jessica', age: 25 },
{ name: 'Ilary', age: 27 },
{ name: 'Frank', age: 70 },
{ name: 'Dan', age: 65 },
{ name: 'Pop', age: 22 },
{ name: 'Maur', age: 68 },
];
let nameOver50 = [];
let nameUnder50 = [];
function check(enter) {
person.filter(({ name, age }) => {
if (age > 50 && enter === 'over') {
nameOver50.push( name );
// nameOver50.push({ name });
// You could alternatively just push the name, if you want an array of the names only
} else if (age < 50 && enter === 'under') {
nameUnder50.push(name);
}
});
console.log(nameUnder50);
console.log(nameOver50);
}
check('over');
check('under');
You're not using the result of filter(), so it should be forEach().
You need to display the appropriate array depending on enter.
const person = [
{ name: 'Jessica', age: 25 },
{ name: 'Ilary', age: 27 },
{ name: 'Frank', age: 70 },
{ name: 'Dan', age: 65 },
{ name: 'Pop', age: 22 },
{ name: 'Maur', age: 68 },
];
let nameOver50 = [];
let nameUnder50 = [];
function check(enter) {
person.forEach(({ name, age }) => {
if (age > 50 && enter === 'over') {
nameOver50.push({ name });
} else if (age < 50 && enter === 'under') {
nameUnder50.push(name);
}
});
if (enter === 'over') {
console.log(nameOver50);
} else {
console.log(nameUnder50);
}
}
check('over');
I have an array of objects (I don't know how many object, maybe 3, maybe 10)
example:
const data = [
{name: 'Jane', age: 25},
{name:'Luke', age: 55},
{name:'Martha', age: '16'},
...and so on
]
now I want to map through this array and create a key-value pair for each, and as a key I want to use a letter of alphabet (starting with c).
expected result is:
{
c:{name: 'Jane', age: 25},
d:{name:'Luke', age: 55},
e:{name:'Martha', age: '16'}
...and so on
}
How to achieve that ?
I am using JS & React
You can easily achieve the result using reduce and String.fromCharCode.
ASCII CODE of c is 99
const data = [
{ name: "Jane", age: 25 },
{ name: "Luke", age: 55 },
{ name: "Martha", age: "16" },
];
const result = data.reduce((acc, curr, i) => {
acc[String.fromCharCode(99 + i)] = curr;
return acc;
}, {});
console.log(result);
Disregarding the why, and the limitations of using letters...
You can map the array, and create a tuples of [letter, object], and then convert them to an object using Object.fromEntries().
To create the letter, add 99 to the current index value (i) to get the current letters ascii code, and then convert it to a letter using String.charFromCode().
const data = [
{name: 'Jane', age: 25},
{name:'Luke', age: 55},
{name:'Martha', age: '16'},
]
const result = Object.fromEntries(
data.map((o, i) => [String.fromCharCode(i + 99), o])
)
console.log(result)
You can do that... (with a simple reduce)
const data =
[ { name: 'Jane', age: 25 }
, { name:'Luke', age: 55 }
, { name:'Martha', age: '16'}
]
let lCod = 'c'.charCodeAt(0)
const res = data.reduce((r,o)=>(r[String.fromCharCode(lCod++)]=o,r),{})
console.log (res)
.as-console-wrapper { max-height: 100% !important; top: 0 }
if your array size is bigger than 24...
with the help of georg's answer
const data =
[ { name: 'nam_0', age: 0 }, { name: 'nam_1', age: 1 }, { name: 'nam_2', age: 2 }, { name: 'nam_3', age: 3 }, { name: 'nam_4', age: 4 }
, { name: 'nam_5', age: 5 }, { name: 'nam_6', age: 6 }, { name: 'nam_7', age: 7 }, { name: 'nam_8', age: 8 }, { name: 'nam_9', age: 9 }
, { name: 'nam_10', age:10 }, { name: 'nam_11', age:11 }, { name: 'nam_12', age:12 }, { name: 'nam_13', age:13 }, { name: 'nam_14', age:14 }
, { name: 'nam_15', age:15 }, { name: 'nam_16', age:16 }, { name: 'nam_17', age:17 }, { name: 'nam_18', age:18 }, { name: 'nam_19', age:19 }
, { name: 'nam_20', age:20 }, { name: 'nam_21', age:21 }, { name: 'nam_22', age:22 }, { name: 'nam_23', age:23 }, { name: 'nam_24', age:24 }
, { name: 'nam_25', age:25 }, { name: 'nam_26', age:26 }, { name: 'nam_27', age:27 }, { name: 'nam_28', age:28 }, { name: 'nam_29', age:29 }
]
, cName = ((lZero = 'c')=>
{
let[a,z,Ln] = [...'az'+lZero].map(c=>c.charCodeAt(0)), mod = z-a+1;
Ln -= a;
return ()=>
{
let n = Ln++, s = '';
while (n>=0)
{
s = String.fromCharCode(n % mod + a ) + s
n = Math.floor(n / mod) - 1;
}
return s
} })()
, res = data.reduce((r,o)=>(r[cName()]=o,r),{})
console.log (res)
.as-console-wrapper { max-height: 100% !important; top: 0 }
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;
}
I have a 5 age fields where user can enter same value they are not validating
while sending to the API. I have to increment the duplicate ages in ech object.
for ex - if user gives ages like 10, 11, 10, 10, 20 i need it as 10,11,12,13,20 like this
Here is the variable having duplicate:
var family = [
{
name: "Mike",
age: 10
},
{
name: "Matt"
age: 13
},
{
name: "Nancy",
age: 13
},
{
name: "Adam",
age: 22
},
{
name: "Jenny",
age: 23
},
{
name: "Nancy",
age: 22
}
];
where every duplicate values comes i have to increment by checking all the ages in each object i need out put like this --> here age 13 and 22 is duplicating i have to check all ages and i have to increment 2nd repeted age by +1 -->
var family = [
{
name: "Mike",
age: 10
},
{
name: "Matt"
age: 13
},
{
name: "Nancy",
age: 14
},
{
name: "Adam",
age: 22
},
{
name: "Jenny",
age: 23
},
{
name: "Nancy",
age: 24
}
];
note my array will have only 5 objects
Try with below code. Hope this will be help u.
var family = [
{
name: "Mike",
age: 10
},
{
name: "Matt",
age: 13
},
{
name: "Nancy",
age: 13
},
{
name: "Adam",
age: 22
},
{
name: "Jenny",
age: 23
},
{
name: "Nancy",
age: 22
}
];
var ind = [];
family.forEach(a => {
cur = a.age;
while (ind[cur] === 1) {
cur++;
}
ind[cur] = 1;
a.age = cur;
});
family.forEach(a => console.log(a.age));
Another update:
var order = family.map((person, index) => {
return { index, person };
}).sort((a, b) => {
if (a.person.age === b.person.age) {
return a.index - b.index;
}
return a.person.age > b.person.age ? 1 : -1;
});
var prevAge = 0;
order.forEach(item => {
if (item.person.age <= prevAge) {
item.person.age = ++prevAge;
}
prevAge = item.person.age;
family.filter(f => f.name === item.person.name)[0].age = item.person.age;
});
Please, try the different cases I put in the demo and check if the results are what you would expect.
Stackblitz: https://stackblitz.com/edit/typescript-far3zq
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);