Count multiple values in JSON object and print to screen - javascript

I have been searching the web for this, and can only seem to locate the Object.keys(obj).length which counts the length of the JSON. I am looking to loop through the JSON and count the values which are the same. In an Array of JSON objects.
[
{
"name": "Bob",
"age": 36
},
{
"name": "Billy",
"age": 18
},
{
"name": "Bob",
"age": 45
}
]
For example, I want to count many Bob there are. I would like to then output to a component like so.
There were 2 Bob
How can this be achieved? In certain situations I will know that there could only be say 4 values for example. SITE, MOBILE, CTV, VIDEO etc, I forsee collecting them and counting them would be easier than counting a random result.

const input = [
{
"name": "Bob",
"age": 36
},
{
"name": "Billy",
"age": 18
},
{
"name": "Bob",
"age": 45
}
]
let sums = input.reduce((a, r) => {
a[r.name] ??= 0
a[r.name] ++
return a
}, {})
console.log(sums)
Now use sums variable to print data in any form you like.

Related

Compare the object fields within array

Compare the age of the objects in an array and keep only the one with the highest age. I've gone through the solution which uses reduce function, but is there any other optimal way other than using reduce?
I am new to javascript, and still learning the concepts.
array: [ { "name": "sample", "age": 22 },{ "name": "sample2", "age": 42 }]
You can achieve this with sort:
const array = [ { "name": "sample", "age": 22 },{ "name": "sample2", "age": 42 }]
const max = array.sort((a, b) => {
return b.age - a.age
})[0]
console.log([max])

How to get list of unique objects from list in javascript

I need a list of unique objects based on a specific key.
const array = [
{"name": "Joe", "age": 42},
{"name": "Donald", "age": 69},
{"name": "John", "age": 42},
]
How can i get a list of unique objects selected from the list assuming i want a list of people with unique ages.
const result = [
{"name": "Joe", "age": 42},
{"name": "Donald", "age": 69}
]
How can this be done in a performant way, is there a better way than iterating through the elements in a foreach and adding it if it does not exist in the resulting array?
One way is to feed the array to a Map where you key them by age. That will eliminate duplicates, only retaining the last in the series of duplicates. Then extract the values again from it:
const array = [{"name": "Joe", "age": 42},{"name": "Donald", "age": 69},{"name": "John", "age": 42}];
const uniques = Array.from(new Map(array.map(o => [o.age, o])).values());
console.log(uniques);
If you want to retain the first of duplicates, then first reverse the array.
Another option is to track seen values, here using a Set passed as a closure and checking for values using its .has() method to return a boolean to a filter() call. This will retain the first seen objects.
const array = [
{ "name": "Joe", "age": 42 },
{ "name": "Donald", "age": 69 },
{ "name": "John", "age": 42 },
]
const unique = (seen => array.filter(o => !seen.has(o.age) && seen.add(o.age)))(new Set());
console.log(unique)

Need to pull names of people who make more than 100,000 from array of objects

I have an array of people that has objects with details about them. For example, "Bob Cratchit" might have an age of 30, a set of skills: "JS, CSS, Python", and a salary of "113000". I want to first check if he has a salary of over 100000, and if so, return his first and last name.
I have tried various methods of .map and .filter, and even tried nesting them. My .map works when I use the console, returning all the names, and the .filter returns all info on people that have > 100000 salary, but I can't seem to do both.
let people = [{
"id": 1,
"firstName": "Frank",
"lastName": "Herbert",
"job": "Lead Software Engineer",
"Skills": ["JavaScript", "C#", "SQL", "HTML", "CSS", "SCRUM
Master"],
"Salary": 120196
},
{
"id": 2,
"firstName": "Joan",
"lastName": "Armorett",
"job": "Jr Software Developer",
"Skills": ["JavaScript", "HTML", "CSS"],
"Salary": 70000
}
// This is the .map function, which will show me all of the names,
regardless of their salary.
let answer = people.map((person) => {return person.firstName});
// This is the .filter function, which will show me all data, not
just names on everyone with a salary of 100000 or higher.
let answer = people.filter((person) => {
return person.Salary > 100000;
});
What I would like is some way to have both: only show results of people who make 100000 or more, and only show those people's names, not other data on them.
The code below uses filter and map functions chained together. Filter returns an array of all the objects having salary property>100000 and map takes the array returned from filter and returns the objects firstname and lastname property . In the end the array is spread out with the spread operator (...) returning it as text.
let people = [{
"id": 1,
"firstName": "Frank",
"lastName": "Herbert",
"job": "Lead Software Engineer",
"Skills": ["JavaScript", "C#", "SQL", "HTML", "CSS", "SCRUMMaster"],
"Salary": 120196
},
{
"id": 2,
"firstName": "Joan",
"lastName": "Armorett",
"job": "Jr Software Developer",
"Skills": ["JavaScript", "HTML", "CSS"],
"Salary": 70000
}]
var t=people.filter((e)=>e.Salary>100000).map((e)=>e.firstName+" "+e.lastName)
console.log(...t)
You could use reduce to do this:
const peopleWhoMakeOverHundredThou = people.reduce((acc, el) => {
if (el.Salary > 100000){
const name = `${el.firstName} ${el.lastName}`
acc.push(name);
}
return acc;
},[])
console.log(peopleWhoMakeOverHundredThou)
If you're only expecting one to be higher and wanted to return a single string instead of any array, you can just adjust as follows:
const peopleWhoMakeOverHundredThou = people.reduce((acc, el) => {
if (el.Salary > 100000){
const name = `${el.firstName} ${el.lastName}`
acc+=name;
}
return acc;
},'')
console.log(peopleWhoMakeOverHundredThou)

Performance related issue for javascript object

I wanted to know if there is some performance issue related in the two below coding paradigms. Which one is the best and why?
var data = [{
"name": "ABC",
"code": 1,
"age": 97
},{
"name": "XYZ",
"code": 12,
"age": 12
},{
"name": "LMN",
"code": 121,
"age": 172
}
];
var response = [];
Method1
data.forEach(function(entry){
var obj = {
"NAME": entry["name"],
"AGE": entry["age"]
};
response.push(obj);
});
Method2
data.forEach(function(entry){
var obj = {};
obj["NAME"] = entry["name"];
obj["AGE"] = entry["age"];
response.push(obj);
});
For output object, I need say suppose, only 10 keys out of 100 keys
The object has many keys in it. Only limited are shown in the example. Which coding standard to choose and why? Please, can anybody explain?
No need to create the objects and then make a Array.prototype.push() for everly loop iteration...
You can directly use Array.prototype.map() instead of Array.prototype.forEach() and better access the object property values by the dot notation:
const data = [{
"name": "ABC",
"code": 1,
"age": 97
},{
"name": "XYZ",
"code": 12,
"age": 12
},{
"name": "LMN",
"code": 121,
"age": 172
}
];
const response = data.map(obj => ({
NAME: obj.name,
AGE: obj.age
}));
console.log(response)
Both approaches are fine and one should not be "faster" than the other, at least not enough to justify using the other one. Use the one you like.
But, if you're still looking for closure. The first one should be faster since it defines the entire object all at one go. There's no "look-ups" the engine have to do. It's all done at one go.
On a separate note, consider using the dot notation, it should be faster since the engine will not have to create strings. So, change
entry["name"]
to
entry.name
Also, if this is your actual code and the purpose is to modify the result to have just name and age and no code. You can do
data.forEach(user => delete user.code)

How to search and select an object in JSON

Consider a JSON like this:
[{
"type": "person",
"name": "Mike",
"age": "29"
},
{
"type": "person",
"name": "Afshin",
"age": "21"
},
{
"type": "something_else",
"where": "NY"
}]
I want to search in the JSON value with a key (for example type='person') and then select a whole object of matched item in JSON. For example when I search for type='person' I expect this value:
[{
"type": "person",
"name": "Mike",
"age": "29"
},
{
"type": "person",
"name": "Afshin",
"age": "21"
}]
Because it's a really big JSON value, I don't want to do a brute-force search in all nodes, so I think the only way is using Regular Expressions but I don't know how can I write a Regex to match something like above.
I'm using NodeJs for the application.
Using underscore.js#where:
var results = _(yourObject).where({ type: 'person' })
If your data set is very very big [e.g. 10k or so], consider filtering / paginating stuff server side.
Plain javascript :
var results = dataset.filter(function(p) {
if(p.type == 'person')
return true;
});
If the requirement is to scan multiple times through the collection, the following one time construction overhead might be of worth.
Use hashing based on values of type.Convert the current data structure to hash map.
var hashMap ={
};
hashMap['person'] =[{},{}];
Hope this helps you.
Use
$.grep(jsonarrayobj,function(n, i){
if(n.type==="person")
{}
})

Categories

Resources