Return min value from array of objects - javascript

I have an array of objects. In each object there is a details property (array) with more than one object - for this example I am only showing one.
I am looking for the rating property in each details and looking to find minimum value (in this example 3.1) ... is there a simpler/cleaner way of achieving this?
const ratings = [{ id: 'ABC', details: [{ type: 'VALUE', rating: 9.5 }] }, { id: 'DEF', details: [{ type: 'VALUE', rating: 3.1 }] }, { id: 'GHI', details: [{ type: 'VALUE', rating: 4.5 }] }]
const ids = ['ABC', 'DEF', 'GHI']
const array = []
ids.forEach(element => {
const valueScore = ratings?.find(r => r.id === element)?.details?.find(c => c.type === 'VALUE')
if (valueScore.rating) {
array.push(valueScore.rating)
}
})
console.log('MIN VALUE', Math.min(...array))

You can use flatMap and then apply math.min to get minimum value:
const ratings = [{ id: 'ABC', details: [{ type: 'VALUE', rating: 9.5 }] }, { id: 'DEF', details: [{ type: 'VALUE', rating: 3.1 },{ type: 'VALUE1', rating: 2.1 }] }, { id: 'GHI', details: [{ type: 'VALUE', rating: 4.5 }] }];
const ids = ['ABC', 'DEF', 'GHI']
console.log(Math.min(...ratings.flatMap(o=>
ids.includes(o.id) ? o.details.flatMap(p=>
p.type=='VALUE' ? p.rating : []) : [])));

You can do something like this:
Why this method is preferred is, you are running the loop perfectly over each ratings item and also through each details array item.
ratings = [
{ id: "ABC", details: [{ type: "VALUE", rating: 9.5 }] },
{
id: "DEF",
details: [{ type: "VALUE", rating: 3.1 }, { type: "VALUE1", rating: 2.1 }]
},
{ id: "GHI", details: [{ type: "VALUE", rating: 4.5 }] }
];
ids = ["ABC", "DEF", "GHI"];
const detailsRatingArr = [];
if (ratings.length === ids.length) {
ratings.forEach(eachRating => {
ids.forEach(eachId => {
if (eachRating.id === eachId) {
eachRating.details.forEach(eachDetail => {
detailsRatingArr.push(eachDetail.rating);
});
}
});
});
}
console.log("DETAILS ARRAY ==>", detailsRatingArr);
detailsRatingArr.sort((a, b) => a - b);
console.log("Minimum Rating ==>", detailsRatingArr[0]);

Related

Filtering array based on selected object in JS

Trying to get the filtered array based on the selected object. How can I loop through damaged array which is inside the object and get the resultant array? I tried to add another condition using .map but it prints the rest of the items as well.
Below is the snippet
const inventory = [{
name: 'Jeep',
id: '100',
damaged: [{
name: 'Wrangler',
id: '200'
},
{
name: 'Sahara',
id: '201'
}
]
}, {
name: 'Audi',
id: '101',
damaged: [{
name: 'Q3',
id: '300'
}]
}]
const purchasedCars = [{
car: 'Jeep',
id: '100'
}, {
car: 'Jeep - Wrangler',
id: '200',
},
{
car: 'Jeep - Sahara',
id: '201'
},
{
car: 'Audi - Q3',
id: '300'
}
]
const selectedCar = purchasedCars[0];
const filterCars = () => {
const result = purchasedCars.filter((inv) => inv.id === selectedCar.id)
console.log('result -->', result);
}
filterCars();
Expected output is
[{
car: 'Jeep',
id: '100'
},
{
car: 'Jeep - Wrangler',
id: '200',
},
{
car: 'Jeep - Sahara',
id: '201'
}]
Could anyone please help?
Trying to read your mind here. Is this what you want?
const inventory = [{
name: 'Jeep',
id: '100',
damaged: [{
name: 'Wrangler',
id: '200'
},
{
name: 'Sahara',
id: '201'
}
]
}, {
name: 'Audi',
id: '101',
damaged: [{
name: 'Q3',
id: '300'
}]
}]
const purchasedCars = [{
car: 'Jeep',
id: '100'
}, {
car: 'Jeep - Wrangler',
id: '200',
},
{
car: 'Jeep - Sahara',
id: '201'
},
{
car: 'Audi - Q3',
id: '300'
}
]
const selectedCar = purchasedCars[0];
const filterCars = () => {
let result;
const parentItem = inventory.filter((inv) => inv.id === selectedCar.id)[0];
if ("damaged" in parentItem) {
result = [selectedCar, ...(parentItem.damaged)];
}
console.log('result -->', result);
}
filterCars();
Note that if you can have more nested car types in the damaged property you would you to call filterCars recursively and pass in the car object. If you also want to filters items that may also be present in the damaged property, then you would first need to use the flatMap method (before the filter).

Creating an array from 2 other arrays

I have two arrays of objects as shown below :
categories = [
{ name: "performance", id: 1 },
{ name: "understanding", id: 2 }
]
queries = [
{ name: "A", categoryId: "1" },
{ name: "B", categoryId: "1" },
{ name: "C", categoryId: "1" },
{ name: "D", categoryId: "2" }
]
Now, using these two arrays of objects, I need following array as a result:
process = [
{ category: "performance", query: [
{ name: "A" },
{ name: "B" },
{ name: "C" }
]},
{ category: "understanding", query: [{ name: "D" }] }
]
I have to match the categoryId with process's id and then create the above array.
I have tried the following way to solve this but could not get desired result.
const test = [];
categories.forEach((element) => {
const r = que.filter((res) => res.categoryId === element.id);
queries.forEach((rt) => {
if (rt.categoryId === element.id) {
test.push({
category: element.name,
query: [{
name: rt.name,
}],
});
}
});
});
Is this possible using any built in array methods in JavaScript?
Thanks in advance
Using Array.reduce, you can group queries by categoryId.
Based on that groupedBy object, using Array.map, you can get the result you want.
const categories = [{
name: "performance",
id: "1"
},{
name: "understanding",
id: "2"
}];
const queries = [{
name: "A",
categoryId: "1"
}, {
name: "B",
categoryId: "1"
}, {
name: "C",
categoryId: "1"
}, {
name: "D",
categoryId: "2"
}];
const groupByQueries = queries.reduce((acc, cur) => {
acc[cur.categoryId] ?
acc[cur.categoryId].push({ name: cur.name })
: acc[cur.categoryId] = [ { name: cur.name } ];
return acc;
}, {});
const result = categories.map(({ name, id }) => ({
category: name,
query: groupByQueries[id]
}));
console.log(result);
categories = [{name: "performance", id: 1},{name: "understanding", id: 2}];
queries = [{name: "A", categoryId: "1"}, {name: "B", categoryId: "1"}, {name: "C", categoryId: "1"}, {name: "D", categoryId: "2"}]
const test = [];
categories.forEach((element) => {
let temp = []
queries.map(item =>{
if(element.id.toString() === item.categoryId)
temp.push({name: item.name})
})
test.push({category:element.name,query:temp})
});
console.log(test)

Filter and Sort an Object Containing Array of Objects While Retaining Empty Arrays

I have an object I want to filter so that trainers with the most electric-type pokemon are listed first, but trainers without any electric-type pokemon are still present (represented as an empty array)
Here's my object:
obj = {
trainer1: [
{ name: 'pikachu', type: 'electric', id: 25 },
{ name: 'zapdos', type: 'electric', id: 145 },
{ name: 'psyduck', type: 'water', id: 54 },
],
trainer2: [
{ name: 'eevee', type: 'normal', id: 133 },
{ name: 'magmar', type: 'fire', id: 126 }
],
trainer3: [
{ name: 'ditto', type: 'normal', id: 132 },
{ name: 'magnemite', type: 'electric', id: 81 }
]
}
Becomes this object:
obj = {
trainer1: [
{ name: 'pikachu', type: 'electric', id: 25 },
{ name: 'zapdos', type: 'electric', id: 145 }
],
trainer3: [
{ name: 'magnemite', type: 'electric', id: 81 }
]
trainer2: [] // Array still present, but empty
}
I know reduce would come in handy here but I'm not sure how to set it up correctly.
This may be the bruteforce solution and there will be better solution than this but i think you can do it like the following way.
const tempArr = Object.keys(obj).map(key=>{
return {
key:key,
value:obj[key].filter(pokemon=>pokemon.type==='electric')
}
})
let newObj = {}
tempArr.sort((a,b)=>b.value.length-a.value.length)
tempArr.forEach(item=>{
newObj[item.key] = item.value
})
console.log(newObj)

Keep all the keys of the object after removing duplicates from a slightly nested array

I have the same issue of this question but my objects have more keys for example:
[{
id: 1
name: "abcd",
value: 123,
type: "foo"
},
{
id: 1
name: "abcd",
value: 321,
type: "faa"
},
{
id: 2
name: "dcba",
value: 456,
type: "baa"
}]
I want to achieve something like this:
[{
id: 1,
name: "abcd",
value: [123, 321],
type: ["foo", "faa"]
},
{
id: 2
name: "dcba",
value: [456],
type: ["baa"]
}]
The extra keys have the same value.
The idea is to group by the id, then map each group of objects, pick the id and name from the 1st object, extract all value and type from all objects in the group, transpose, and zip to an another object, and merge them.
const { pipe, groupBy, prop, values, map, converge, merge, head, pick, props, transpose, zipObj } = R
const fn = pipe(
groupBy(prop('id')), // groupBy the id
values, // convert the object of groups to array of groups
map(converge(merge, [ // map each group by merging the results of...
pipe(head, pick(['id', 'name'])), // getting the id and name from the 1st item
pipe(map(props(['value', 'type'])), transpose, zipObj(['value', 'type'])) // extract the value and type and zipping to an object
]))
)
const data = [{
id: 1,
name: "abcd",
value: 123,
type: "foo"
},
{
id: 1,
name: "abcd",
value: 321,
type: "faa"
},
{
id: 2,
name: "dcba",
value: 456,
type: "baa"
}]
const result = fn(data)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script>
You can grab the distinct id , loop over them and group them using filter and map
let data = [{
id: 1,
name: "abcd",
value: 123,
type: "foo"
},
{
id: 1,
name: "abcd",
value: 321,
type: "faa"
},
{
id: 2,
name: "dcba",
value: 456,
type: "baa"
}];
//grab unique
let distinct = [...new Set(data.map(a => a.id))];
let grouped = distinct.map(d => {
let filtered=data.filter(d1 => d1.id === d);
return {
id: d,
name: filtered.map(d2 => d2.name)[0],
value: [...new Set(filtered.map(d2 => d2.value))],
type: [...new Set(filtered.map(d2 => d2.type))]
}
});
console.log(grouped);

How to transform an array in to another array

I nave an array:
const arr = [
{ name: "aa", type: "total", count: 28394 },
{ name: "aa", type: "featured", count: 4 },
{ name: "aa", type: "noAnswers", count: 5816 },
{ name: "ba", type: "total", count: 148902 },
{ name: "ba", type: "featured", count: 13 },
{ name: "ba", type: "noAnswers", count: 32527 },
{ name: "cc", type: "total", count: 120531 },
{ name: "cc", type: "featured", count: 6 },
{ name: "cc", type: "noAnswers", count: 24170 }
];
const arrResult = [
{ name: "aa", total: 28394, featured: 4, noAnswers: 5816 },
{ name: "ba", total: 148902, featured: 13, noAnswers: 32527 },
{ name: "cc", total: 120531, featured: 6, noAnswers: 24170 }
];
I come up with this code:
let output = [];
const unique = [...new Set(arr.map(item => item.name))];
for(const key of unique) {
let result = arr.filter(x => {
return x.name === key;
});
output.push({
name: key,
// need to get the rest of the properties here
// total
// featured
// noAnswers
});
}
The only one thing I can not figure out is how to get the property names.
Any ideas?
You can try something like this:
Idea:
Create a hashMap so you can group objects via name.
Then, add necessary properties to this group.
Finally, loop over keys and create final object with name property added back.
const arr = [ { name: "aa", type: "total", count: 28394 }, { name: "aa", type: "featured", count: 4 }, { name: "aa", type: "noAnswers", count: 5816 }, { name: "ba", type: "total", count: 148902 }, { name: "ba", type: "featured", count: 13 }, { name: "ba", type: "noAnswers", count: 32527 }, { name: "cc", type: "total", count: 120531 }, { name: "cc", type: "featured", count: 6 }, { name: "cc", type: "noAnswers", count: 24170 } ];
const hashMap = arr.reduce((acc, item) => {
acc[item.name] = acc[item.name] || {};
acc[item.name][item.type] = item.count;
return acc;
}, {});
const result = Object.keys(hashMap).map((name) => Object.assign({}, {name}, hashMap[name] ));
console.log(result)
Working:
What I'm doing is I'm creating a new object for every new name. So, this: acc[item.name] = acc[item.name] || {}; checks if the entry is unavailable or not.
If unavailable, return a new object.
If available, return same object's reference.
So for any given name, you will only refer to same object.
Now this: acc[item.name][item.type] = item.count sets the properties. As we are referring to same object, you are setting property in one place. So if you have duplicate entries, say
[
{ name: "aa", type: "total", count: 28394 },
{ name: "aa", type: "total", count: 123},
]
output will have total: 123 instead.
So, at the end, you have a structure like:
{
aa: {
total: <something>,
feature: <something>,
...
}
}
Now all you have to do is merge the name in this object and return the value. You can also create the object with name property as default (as done by adiga). Thats something I didn't think while answering. So crediting instead of answering.
You can use reduce and destructuring like this:
The idea is to create an object with key as the name property and value as the final objects you need in the output. So, that you can simply use Object.values to get the final array:
const arr=[{name:"aa",type:"total",count:28394},{name:"aa",type:"featured",count:4},{name:"aa",type:"noAnswers",count:5816},{name:"ba",type:"total",count:148902},{name:"ba",type:"featured",count:13},{name:"ba",type:"noAnswers",count:32527},{name:"cc",type:"total",count:120531},{name:"cc",type:"featured",count:6},{name:"cc",type:"noAnswers",count:24170}];
const merged = arr.reduce((acc,{name,type,count}) =>
((acc[name] = acc[name] || {name})[type] = count, acc)
,{})
console.log(Object.values(merged))
This is equivalent to :
const arr=[{name:"aa",type:"total",count:28394},{name:"aa",type:"featured",count:4},{name:"aa",type:"noAnswers",count:5816},{name:"ba",type:"total",count:148902},{name:"ba",type:"featured",count:13},{name:"ba",type:"noAnswers",count:32527},{name:"cc",type:"total",count:120531},{name:"cc",type:"featured",count:6},{name:"cc",type:"noAnswers",count:24170}];
/* Our goal is to create a merged object like this:
{
"aa": {
"name": "aa",
"total": 28394,
"featured": 4,
"noAnswers": 5816
},
"ba": {
"name": "ba",
"total": 148902,
....
},
"cc": {
"name": "cc",
......
}
}
The advantage of using object accumulator is we can access it like this: acc[name]
*/
const merged = arr.reduce((acc, {name,type,count} /*Destructuring*/) => {
/* if the accumulator doesn't have the current "name" key,
create new object
else use the existing one;
{name} is same as {name: name}
*/
acc[name] = acc[name] || {name};
/* To the inner object,
add a key with the "type" value and assign it to "count" value
*/
acc[name][type] = count;
// return the accumulator
return acc;
}, {})
// use Object.values to get the value part of the merged obejct into an array
console.log(Object.values(merged))
var op = {name : key};
for(i=0; i < result.length; i++){
op[result[i].type] = result[i].count;
}
output.push(op);
just adding this will work fine. However your code is not the most efficient.
Hashing based on name will make it faster
const arr = [
{ name: "aa", type: "total", count: 28394 },
{ name: "aa", type: "featured", count: 4 },
{ name: "aa", type: "noAnswers", count: 5816 },
{ name: "ba", type: "total", count: 148902 },
{ name: "ba", type: "featured", count: 13 },
{ name: "ba", type: "noAnswers", count: 32527 },
{ name: "cc", type: "total", count: 120531 },
{ name: "cc", type: "featured", count: 6 },
{ name: "cc", type: "noAnswers", count: 24170 }
];
let output = [];
const unique = [...new Set(arr.map(item => item.name))];
for(const key of unique) {
let result = arr.filter(x => {
return x.name === key;
});
var op = {name : key};
for(i=0; i < result.length; i++){
op[result[i].type] = result[i].count;
}
output.push(op);
}
console.log(output);
The following is the most efficient way of doing it :
const arr = [
{ name: "aa", type: "total", count: 28394 },
{ name: "aa", type: "featured", count: 4 },
{ name: "aa", type: "noAnswers", count: 5816 },
{ name: "ba", type: "total", count: 148902 },
{ name: "ba", type: "featured", count: 13 },
{ name: "ba", type: "noAnswers", count: 32527 },
{ name: "cc", type: "total", count: 120531 },
{ name: "cc", type: "featured", count: 6 },
{ name: "cc", type: "noAnswers", count: 24170 }
];
var hash = {};
var result = [];
for(var i=0; i < arr.length; i++){
if(!arr[i].name in hash)
hash[arr[i].name] = {}
let temp = {};
temp[arr[i].type] = arr[i].count;
hash[arr[i].name] = Object.assign(temp, hash[arr[i].name]);
}
for(var key in hash)
result.push({name : key, ...hash[key]})
console.log(result)
You can use find operator of javascript to grab the desired row from arrResult Change your code like below-
for(const key of unique) {
let result = arr.filter(x => {
return x.name === key;
});
var currResult = arrResult.find(x => x.name == key);
output.push({
name: key,
// need to get the rest of the properties here
total: currResult.total,
featured: currResult.featured,
noAnswers: currResult.noAnswers
});
}
JSFiddle: https://jsfiddle.net/ashhaq12345/z8royg5w/
const arr = [
{ name: "aa", type: "total", count: 28394 },
{ name: "aa", type: "featured", count: 4 },
{ name: "aa", type: "noAnswers", count: 5816 },
{ name: "ba", type: "total", count: 148902 },
{ name: "ba", type: "featured", count: 13 },
{ name: "ba", type: "noAnswers", count: 32527 },
{ name: "cc", type: "total", count: 120531 },
{ name: "cc", type: "featured", count: 6 },
{ name: "cc", type: "noAnswers", count: 24170 }
];
const names = [...new Set(arr.map(item => item.name))]
const output = {};
names.forEach(name => {output[name] = {}});
arr.forEach(item => {
output[item.name][item.type] = item.count
});
const result = Object.entries(output).map(([name, rest]) => ({name, ...rest}))
console.log(result);
const arrResult = [
{ name: "aa", total: 28394, featured: 4, noAnswers: 5816 },
{ name: "ba", total: 148902, featured: 13, noAnswers: 32527 },
{ name: "cc", total: 120531, featured: 6, noAnswers: 24170 }
];
You can simply use for loop to iterate over your array and take a temp array and take map and fill the map using required data and then push your map into temp array like following.
const arr = [
{ name: "aa", type: "total", count: 28394 },
{ name: "aa", type: "featured", count: 4 },
{ name: "aa", type: "noAnswers", count: 5816 },
{ name: "ba", type: "total", count: 148902 },
{ name: "ba", type: "featured", count: 13 },
{ name: "ba", type: "noAnswers", count: 32527 },
{ name: "cc", type: "total", count: 120531 },
{ name: "cc", type: "featured", count: 6 },
{ name: "cc", type: "noAnswers", count: 24170 }
];
let result = [];
for( var i = 0; i < arr.length; i++)
{
let data = {};
if( arr[i].type == 'total')
{
data.name = arr[i].name;
data.total = arr[i].count;
data.featured = arr[i+1].count;
data.noAnswers = arr[i+2].count;
result.push(data);
}
}
console.log(result);

Categories