How to groupBy array of objects based on properties in vanilla javascript - javascript

How do you groupBy array of objects based on specific properties in vanilla javascript? For example this given:
const products = [
{
category: "Sporting Goods",
price: "$49.99",
stocked: true,
name: "Football"
},
{
category: "Sporting Goods",
price: "$9.99",
stocked: true,
name: "Baseball"
},
{
category: "Sporting Goods",
price: "$29.99",
stocked: false,
name: "Basketball"
},
{
category: "Electronics",
price: "$99.99",
stocked: true,
name: "iPod Touch"
},
{
category: "Electronics",
price: "$399.99",
stocked: false,
name: "iPhone 5"
},
{ category: "Electronics", price: "$199.99", stocked: true, name: "Nexus 7" }
];
i want to run a reduce function that would result to a new array of objects like this:
Intended Output:
const categorize = [
{
category:"Sporting Goods",
products: [
{
name:"Football",
price: "$49.99",
stocked: true
},
{
name:"Baseball",
price: "$9.99",
stocked: true
},
{
name:"Basketball",
price: "$29.99",
stocked: true
}
]
},
{
category: "Electronics",
products: [
{
name: "iPod Touch",
price: "$99.99",
stocked: true
},
{
name: "iPhone 5",
price: "$399.99",
stocked: false
},
{
name: "Nexus 7",
price: "$199.99",
stocked: true
}
]
}
]
i based my solution from the tutorial here: https://www.consolelog.io/group-by-in-javascript/ using the reduce function.
Here's my code:
const groupBy = (arr,prop)=>{
return arr.reduce((groups,item)=>{
let val = item[prop];
groups[val] = groups[val]||[];
groups[val].push(item);
return groups
},{});
}
const categorize = groupBy(products,'category');
console.log(categorize);
/* returns an Object like
Object {Sporting Goods: Array[3], Electronics: Array[3]}
however it's not the intended output.
*/
I tried to return Object.values(obj) or Object.entries(obj) inside the groupBy function but it just returns an array of 2 arrays like [Array[3],Array[3]] and if i set the initial value (2nd parameter of reduce) to empty [] instead of {}, the output is just an empty array. Need help, thanks!

Because you want an array containing objects (rather than just an array of plain values), create a { category, products: [] } object if it doesn't exist in the accumulator:
const products=[{category:"Sporting Goods",price:"$49.99",stocked:!0,name:"Football"},{category:"Sporting Goods",price:"$9.99",stocked:!0,name:"Baseball"},{category:"Sporting Goods",price:"$29.99",stocked:!1,name:"Basketball"},{category:"Electronics",price:"$99.99",stocked:!0,name:"iPod Touch"},{category:"Electronics",price:"$399.99",stocked:!1,name:"iPhone 5"},{category:"Electronics",price:"$199.99",stocked:!0,name:"Nexus 7"}];
const output = Object.values(
products.reduce((a, { category, ...item }) => {
if (!a[category]) {
a[category] = { category, products: [] };
}
a[category].products.push(item);
return a;
}, {})
);
console.log(output);

function (){
var map = {};
products.forEach((p) => {
if (map[p.category]) {
var c = p.category;
delete p.category;
map[c].push(p);
} else {
var c = p.category;
delete p.category;
map[c]=[c]
}
});
Object.keys(map).forEach((m) => {
ans.push({category:m, products: map[m]})
})
}
you can collect in one go products and map them.
Then make your resultinng array

Related

How to return a new array of objects that contains merged data from source and target?

I want to compare an oldItems array of objects and if id matches the id in my updatedItems array of objects, I want to update the object, copying over the property from oldItems if there is no value in updatedItems for that key or if that property is not defined, and replacing the oldItems object property with the updatedItems object property if there IS a value. I want to store all the changes in a result variable and log result to the console.
The result variable should contain exactly an object with id: 1, the new sandwich name, and the old price, as well as id: 2 with the new price and the new name.
const oldItems = [
{
id: 0,
name: "peanut butter sandwich",
price: 3
},
{
id: 1,
name: "cheese sandwich",
price: 4
},
{
id: 2,
name: "chicken sandwich",
price: 6
}
]
const updatedItems =
[{
id: 1,
name: "grilled cheese sandwich"
}, {
id: 2,
price: 5,
name: "chicken and waffles sandwich"
}]
I tried:
let result = oldItems.map((item, i) => Object.assign({}, item, updatedItems[i]));
console.log(result);
I'm not completely certain of your use-case, but this will produce the result you describe.
oldItems.map(o => {
const update = updatedItems.find(u => u.id === o.id);
if (update) return {
...o,
...update
}
}).filter(x => x)
result :
[
{ id: 1, name: 'grilled cheese sandwich', price: 4 },
{ id: 2, name: 'chicken and waffles sandwich', price: 5 }
]
First, your code maps over the wrong array, you should be mapping updatedItems.
Second, you can't use the same i for both arrays, since the items with the same id are not at the same indexes. Use find() to search the array for the id.
In ES6 you can use ... to merge objects instead of Object.assign().
const oldItems = [{
id: 0,
name: "peanut butter sandwich",
price: 3
},
{
id: 1,
name: "cheese sandwich",
price: 4
},
{
id: 2,
name: "chicken sandwich",
price: 6
}
];
const updatedItems = [{
id: 1,
name: "grilled cheese sandwich"
}, {
id: 2,
price: 5,
name: "chicken and waffles sandwich"
}];
let result = updatedItems.map((item) => ({
...oldItems.find(el => el.id == item.id),
...item
}));
console.log(result);

How to compare object values in an array of objects?

I am trying to compare an array of objects. Each object has the same keys, but varying values for each key. I would like to create a function that compares each object for similar key value pairs.
I only care about the quality and location keys for each object, and I want to compare all objects against these two keys.
For example, if the first and second object in the array of objects contains the same value for two keys, I would like to create an output array of objects that summarizes each grouping.
Explanation: Object one and two contain the same value for quality and location. Since the third object does not, a new object should be created that summarizes the information from the first and second objects. That new object should contains an array of all fruit names and and array of all tags. The output object is shown below.
// Input
data = [
{
id: '1',
fruit: 'granny smith',
quality: 'good',
location: 'chicago',
tags: ['green', 'sweet'],
},
{
id: '2',
fruit: 'Fuji',
quality: 'good',
location: 'chicago',
tags: ['red', 'tart'],
},
{
id: '3',
fruit: 'gala',
quality: 'bad',
location: 'san diego',
tags: ['tall', 'thin'],
},
];
// Function
function compareObjects(arr) {
const grouped = [];
// Loop over every fruit
const similarObjects = arr.filter((obj, id) => {
// create structure for each common object
let shape = {
id,
fruits: [],
quality: '',
tags: [],
};
arr.forEach((item) => {
// Return a new shape object that contains all fruit names, tags, and quality
if (item.quality == obj.quality && item.location == obj.location) {
shape.id = id;
shape.fruits.push(item.fruit);
shape.fruits.push(obj.fruit);
shape.quality = item.quality;
shape.tags.push(item.tag);
shape.tags.push(obj.tag);
return shape;
}
});
return obj;
});
return similarObjects;
}
console.log(compareObjects(data));
// Output
const output = [
{
id: 'a',
fruits: ['grann smith', 'fuji'],
quality: 'good',
tags: ['green', 'sweet', 'red', 'tart'],
},
...
];
You can group the data by their quality and location using Array.prototype.reduce and filter the groups where the length is greater than one.
const
data = [
{ id: "1", fruit: "granny smith", quality: "good", location: "chicago", tags: ["green", "sweet"] },
{ id: "2", fruit: "Fuji", quality: "good", location: "chicago", tags: ["red", "tart"] },
{ id: "3", fruit: "gala", quality: "bad", location: "san diego", tags: ["tall", "thin"] },
],
output = Object.values(
data.reduce((r, d) => {
const key = `${d.quality}+${d.location}`;
if (!r[key]) {
r[key] = { id: d.id, fruits: [], quality: d.quality, location: d.location, tags: [] };
}
r[key].fruits.push(d.fruit);
r[key].tags.push(...d.tags);
return r;
}, {})
).filter((d) => d.fruits.length > 1);
console.log(output);
If you also wish to only keep unique fruits then you can map over the resultant array and remove the duplicates using a Set.
const
data = [
{ id: "1", fruit: "granny smith", quality: "good", location: "chicago", tags: ["green", "sweet"] },
{ id: "2", fruit: "Fuji", quality: "good", location: "chicago", tags: ["red", "tart"] },
{ id: "3", fruit: "gala", quality: "bad", location: "san diego", tags: ["tall", "thin"] },
],
output = Object.values(
data.reduce((r, d) => {
const key = `${d.quality}+${d.location}`;
if (!r[key]) {
r[key] = { id: d.id, fruits: [], quality: d.quality, location: d.location, tags: [] };
}
r[key].fruits.push(d.fruit);
r[key].tags.push(...d.tags);
return r;
}, {})
)
.filter((d) => d.fruits.length > 1)
.map((d) => ({ ...d, fruits: [...new Set(d.fruits)] }));
console.log(output);
Other relevant documentations:
Spread syntax (...)
Array.prototype.push
Array.prototype.filter
Object.values

How to loop over a an array that is already inside a map function without duplicating the contents

I have the following code with the following arrays. I want to loop through both of them and pull out some data, and put them inside a final array. I am able to do that, but the contents are duplicated. I tried reading about reduce but don't quite understand it, and am not sure if it's the right solution. I have also setup a jsfiddle
https://jsfiddle.net/anders_kitson/Lcqn6fgd/
var lineItems = [{
id: 'li_1HyhAZHk5l44uIELgsMWqHqB',
object: 'item',
amount_subtotal: 7500,
amount_total: 7500,
currency: 'cad',
description: 'The Spencer',
price: [Object],
quantity: 1
},
{
id: 'li_1HyhAZHk5l44uIELeNUsiZPu',
object: 'item',
amount_subtotal: 7500,
amount_total: 7500,
currency: 'cad',
description: 'The Gertie',
price: [Object],
quantity: 1
}
]
var arr = [{
id: 'prod_IS1wY1JvSv2CJg',
object: 'product',
active: true,
attributes: [],
created: 1606248785,
description: 'Shelf Set',
images: [
'https://files.stripe.com/links/fl_test_raNEqk9ZhzX3WdQsnvXX4gFq'
],
livemode: false,
metadata: {},
name: 'The Spencer',
statement_descriptor: null,
type: 'service',
unit_label: null,
updated: 1606248785
},
{
id: 'prod_IS299dMnC13Ezo',
object: 'product',
active: true,
attributes: [],
created: 1606249543,
description: 'Shelf Set',
images: [
'https://files.stripe.com/links/fl_test_QPbrP76uNn4QadgcUwUnkmbe'
],
livemode: false,
metadata: {},
name: 'The Gertie',
statement_descriptor: null,
type: 'service',
unit_label: null,
updated: 1606249543
}
];
let productArr = [];
arr.map((item) => {
lineItems.map((line) => {
productArr.push({
image: item.images[0],
name: item.name,
price: line.amount_total,
});
});
});
console.log(productArr);
This is the output I get where you can see the array repeats the values, and I know I have coded it this way I just don't know how to fix it.
[{
image: "https://files.stripe.com/links/fl_test_raNEqk9ZhzX3WdQsnvXX4gFq",
name: "The Spencer",
price: 7500
}, {
image: "https://files.stripe.com/links/fl_test_raNEqk9ZhzX3WdQsnvXX4gFq",
name: "The Spencer",
price: 7500
}, {
image: "https://files.stripe.com/links/fl_test_QPbrP76uNn4QadgcUwUnkmbe",
name: "The Gertie",
price: 7500
}, {
image: "https://files.stripe.com/links/fl_test_QPbrP76uNn4QadgcUwUnkmbe",
name: "The Gertie",
price: 7500
}]
To Be more clear this is the output that I want
[{
image: "https://files.stripe.com/links/fl_test_raNEqk9ZhzX3WdQsnvXX4gFq",
name: "The Spencer",
price: 7500
}, {
image: "https://files.stripe.com/links/fl_test_QPbrP76uNn4QadgcUwUnkmbe",
name: "The Gertie",
price: 7500
},
]
I have tried the suggestion in the comments with the following
let b
arr.map((item) => {
b = lineItems.map((line) => {
return {
image: item.images[0],
name: item.name,
price: line.amount_total,
};
});
});
but it returns the same ones twice
[{
image: "https://files.stripe.com/links/fl_test_QPbrP76uNn4QadgcUwUnkmbe",
name: "The Gertie",
price: 7500
}, {
image: "https://files.stripe.com/links/fl_test_QPbrP76uNn4QadgcUwUnkmbe",
name: "The Gertie",
price: 7500
}]
Although not expressed directly in your question, it seems you're looking to do a join in javascript. The only things I see relating the two are 'name' in products and 'description' in the line items. So do a loop join on that.
Here's some sample code using your example but stripped down only to what's relevant:
var lineItems = [
{ amount_total: 7500, description: 'The Spencer' },
{ amount_total: 7500, description: 'The Gertie' }
]
var arr = [
{ images: ['Spencer Image 1'], name: 'The Spencer' },
{ images: ['Gertie Image 1'], name: 'The Gertie' }
]
let joined = arr
.flatMap(a => lineItems.map(li => ({a, li})))
.filter(obj => obj.a.name == obj.li.description)
.map(obj => ({
image: obj.a.images[0],
name: obj.a.name,
price: obj.li.amount_total
}));
console.log(joined);
Being a loop join, it may not be that efficient. To do a hash join is a little more involved. You can look through the source code of my developing project
fluent-data, or it might even be useful to you to use it directly if you can follow the documentation.
You can use a single map call and reference your second lineItems array either by index, if you know that the two arrays are the same length and order
const output = arr.map((o, i) => ({
name: o.name,
image: o.images[0],
price: lineItems[i].amount_total}
));
or by using find() to retrieve the relevant object.
const outputUsingFind = arr.map(o => {
const lineItem = lineItems.find(item => item.description === o.name);
// ** add lineItem valid check here **
return {
name: o.name,
image: o.images[0],
price: lineItem.amount_total};
});
var lineItems = [{amount_subtotal: 7500,amount_total: 700,description: 'The Spencer',},{amount_subtotal: 7500,amount_total: 500,description: 'The Gertie',}];
var arr = [{images: ['spencer image'],name: 'The Spencer',},{images: ['gertie image'],name: 'The Gertie'}];
// since your arrays are ordered the same you can access the second object using
// the index passed from map.
const output = arr.map((o, i) => ({
name: o.name,
image: o.images[0],
price: lineItems[i].amount_total}
));
console.log(output);
// if the two arrays are not in the same order you can use find() to retrieve
// the second object by property (you'll need to check
const outputUsingFind = arr.map(o => {
const lineItem = lineItems.find(item => item.description === o.name);
// ** add lineItem valid check here **
return {
name: o.name,
image: o.images[0],
price: lineItem.amount_total};
});
console.log(outputUsingFind);
.as-console-wrapper { max-height: 100% !important; top: 0; }

In array of objects count grouped values by certain key

I have a following data:
const data2 = [
{
App: "testa.com",
Name: "TEST A",
Category: "HR",
Employees: 7
},
{
App: "testd.com",
Name: "TEST D",
Category: "DevOps",
Employees: 7
},
{
App: "teste.com",
Name: "TEST E",
Category: "DevOps",
Employees: 7
},
{
App: "testf.com",
Name: "TEST F",
Category: "Business",
Employees: 7
}
]
I want to get the count of distinct categories: Right now I am getting the list of all distinct categories but I'm unable to compute their count.
Following snippet give me the Distinct Category:
let uniqueCategory = [];
for(let i = 0; i < result.data.length; i++){
if(uniqueCategory.indexOf(result.data[i].Category) === -1){
uniqueCategory.push(result.data[i].Category);
}
}
What changes should I make to get the Counts of those Categories in the uniqueCategory - something like following:
uniqueCategory = [
{Category: "DevOps", count: 5},
{Category: "Business", count: 4},
....
{}
]
Your approach implies looping your source array (with .indexOf()) every iteration of for(..-loop. That will slow down unnecessarily look up process.
Instead, you may employ Array.prototype.reduce() to traverse your source array and build up the Map, having Category as a key and object of desired format as a value, then extract Map.prototype.values() into resulting array.
That will perform much faster and scale better.
const src = [{App:"testa.com",Name:"TEST A",Category:"HR",Employees:7},{App:"testd.com",Name:"TEST D",Category:"DevOps",Employees:7},{App:"teste.com",Name:"TEST E",Category:"DevOps",Employees:7},{App:"testf.com",Name:"TEST F",Category:"Business",Employees:7}],
result = [...src
.reduce((r, {Category}) => {
const cat = r.get(Category)
cat ? cat.count ++ : r.set(Category, {Category, count: 1})
return r
}, new Map)
.values()
]
console.log(result)
.as-console-wrapper{min-height:100%;}
The easiest way to do it is to use Array.prototype.reduce
const arr = [ ... ];
const output = arr.reduce((result, obj) => {
if (!result[obj.category]) {
result[obj.category] = 0;
}
result[obj.category]++;
return result;
}, {});
console.log(output); // this should log the similar output you want
Here's another alternative using .map and Set:
const src = [
{
App: "testa.com",
Name: "TEST A",
Category: "HR",
Employees: 7
},
{
App: "testd.com",
Name: "TEST D",
Category: "DevOps",
Employees: 7
},
{
App: "teste.com",
Name: "TEST E",
Category: "DevOps",
Employees: 7
},
{
App: "testf.com",
Name: "TEST F",
Category: "Business",
Employees: 7
}
];
const categories = src.map(obj => obj.Category);
const distinctCategories = [...new Set(categories)];
console.log(distinctCategories.length);

Map value of an attribute in one object array to an attribute in another object array Javascript

I have two arrays of objects:
courses = [ { _id: 999, courseCode: "Eng1" },
{ _id: 777, courseCode: "Sci1" },
{ _id: 666, courseCode: "Eng2" },
{ _id: 888, courseCode: "Sci2" } ]
sectionCourses = [ { sectionCode: "1A", courseId: "999" },
{ sectionCode: "1A", courseId: "777" },
{ sectionCode: "2A", courseId: "666" },
{ sectionCode: "2A", courseId: "888" } ]
I want to filter the courses array in such a way that it contains only the courses that are not in a section.
For example if I select section with sectionCode: "2A", the courses array should only contain
courses = [ { _id: 999, courseCode: "Eng1" },
{ _id: 777, courseCode: "Sci1" },
{ _id: 888, courseCode: "Sci2" } ]
I tried to do this way:
courses = courses.filter(c => !(sectionCourses.includes(c._id)))
but I know this is incomplete because I can't figure out how to access courseId in sectionCourses.
Please help.
You can't use .includes() method to find the whole object by its _id, includes compares the whole objects and doesn't search for a specific property.
What you can do here is to get an array of courseIds to be ignored based on the sectionCode you provided, and then filter the courses that their _id doesn't exist in this array of ids:
function getCourses(catCode) {
var coursesIdstoIgnore = sectionCourses.filter(s => s.sectionCode === catCode).map(s => s.courseId);
return courses.filter(c => coursesIdstoIgnore.indexOf(c["_id"].toString()) == -1);
}
Demo:
var courses = [{
_id: 999,
courseCode: "Eng1"
},
{
_id: 777,
courseCode: "Sci1"
},
{
_id: 666,
courseCode: "Eng2"
},
{
_id: 888,
courseCode: "Sci2"
}
];
var sectionCourses = [{
sectionCode: "1A",
courseId: "999"
},
{
sectionCode: "1A",
courseId: "777"
},
{
sectionCode: "2A",
courseId: "666"
},
{
sectionCode: "2A",
courseId: "888"
}
];
function getCourses(catCode) {
var cousesIdstoIgnore = sectionCourses.filter(s => s.sectionCode === catCode).map(s => s.courseId);
console.log(cousesIdstoIgnore);
return courses.filter(c => cousesIdstoIgnore.indexOf(c["_id"].toString()) == -1);
}
var results = getCourses("2A");
console.log(results);
courses.filter(course => sectionCourses.find(section => +section.courseId === +course._id))
Note how i use the +operator before of the courseId and _id properties. this automatically turns a String typed number into a Number.
e.g
+"1" = 1
+1 = 1
This is very useful for slight comparison gotchas when using ===
Note Array.find() doesn't work with IE

Categories

Resources