Javascript count between 2 arrays - javascript

I have 2 arrays objects and I need to do a count of home many types of card we have.
The first object contains all the car id's and the second list contains the types of cars.
Here is the data:
var arr = {
"categories": [{
"id": "100",
"name": "category name",
"car_id": "1"
}, {
"id": "192",
"name": "category name here",
"car_id": "25"
}, {
"id": "192",
"name": "category name here",
"car_id": "27"
}]
};
var arr2 = {
"cars": [{
"id": "1",
"name": "car name",
"car_id": "1",
"type": "ford"
}, {
"id": "4",
"name": "name 2",
"car_id": "25",
"type": "ford"
}, {
"id": "4",
"name": "name 2",
"car_id": "27",
"type": "fiat"
}]
};
There's only 5 types of cars so I have 5 variables:
var:
ford,
fiat,
mazda,
mini,
mg
So, what I need to end up with is something like this:
ford: 2;
fiat: 1;
mazda: 0;
mini: 0;
mg: 0;
How can I do this?

If your number of types are fixed, then try this approach
Make an map first
var map = {
ford: 0,
fiat: 0,
mazda: 0,
mini: 0,
mg: 0
};
Now iterate the arrays and count by types
arr2.cars.forEach( function( item ){
map[ item.type ]++;
});
your map is populated with the values now.
var arr2 = {
"cars": [{
"id": "1",
"name": "car name",
"car_id": "1",
"type": "ford"
}, {
"id": "4",
"name": "name 2",
"car_id": "25",
"type": "ford"
}, {
"id": "4",
"name": "name 2",
"car_id": "27",
"type": "fiat"
}]
};
var map = {
ford: 0,
fiat: 0,
mazda: 0,
mini: 0,
mg: 0
};
arr2.cars.forEach(function(item) {
map[item.type] ++;
});
console.log(map);

var arr = {
"categories": [{
"id": "100",
"name": "category name",
"car_id": "1"
}, {
"id": "192",
"name": "category name here",
"car_id": "25"
}, {
"id": "192",
"name": "category name here",
"car_id": "27"
}]
};
var arr2 = {
"cars": [{
"id": "1",
"name": "car name",
"car_id": "1",
"type": "ford"
}, {
"id": "4",
"name": "name 2",
"car_id": "25",
"type": "ford"
}, {
"id": "4",
"name": "name 2",
"car_id": "27",
"type": "fiat"
}]
};
var carCount, typeCount;
arr.categories.forEach(function(item){
if(item.hasOwnProperty("car_id")){
carCount = arr.categories.length;
}
});
arr2.cars.forEach(function(item){
if(item.hasOwnProperty("type")){
typeCount = arr2.cars.length;
}
});
console.log(carCount);
console.log(typeCount);
https://jsfiddle.net/Law7rzc2/

All you need is
countBy(arr2.cars, 'type')
The implementation of countBy is left as an exercise.

Array.prototype.reduce is your go-to for this kind of array computation. A Map will help you keep track of unique car makes as you iterate thru the array of cars.
var obj2 = {
"cars": [{
"id": "1",
"name": "car name",
"car_id": "1",
"type": "ford"
}, {
"id": "4",
"name": "name 2",
"car_id": "25",
"type": "ford"
}, {
"id": "4",
"name": "name 2",
"car_id": "27",
"type": "fiat"
}]
};
const typeStat = cars => {
let map = cars.reduce((m, {type}) =>
m.set(type, (m.get(type) || 0) + 1), new Map());
return Array.from(map, ([make, count]) => ({make, count}));
};
let stats = typeStat(obj2.cars)
console.log(stats);
Output
[
{
"make": "ford",
"count": 2
},
{
"make": "fiat",
"count": 1
}
]

Related

Is this the best approach to restructure an array and reorganize it based off a sub array's value

I have the below array which has a sub array of categories, I would like to output the array over and over but grouping the items into another array based on their related categories
testData2: any = [{
"id": 0,
"name": "XyZ",
"category": [ {
"title": "horse"
}, {
"title": "food"
}]
}, {
"id": 2,
"name": "something 2",
"category": [{
"title": "fishing"
}, {
"title": "horse"
}, {
"title": "food"
}]
},
{
"id": 3,
"name": "something 3",
"category": [{
"title": "horse"
}]
}, {
"id": 4,
"name": "something 4",
"category": [{
"title": "food"
}, {
"title": "beer"
}]
}, {
"id": 5,
"name": "something 4",
"category": [{
"title": "fishing"
}]
}
]
So far I have this which works, but i cant help wonder if there is some new JS magic which may be more perfomant to accomplish this ?
let newArray = [];
for (let x = 0; x < this.testData2.length; x++) {
let parent = this.testData2[x];
let child = parent.category;
for (let y = 0; y < child.length; y++) {
let cat = child[y];
let format = parent
newArray.push({ group_heading: cat.title, services: [format] })
}
}
let finalOutput = newArray.reduce((acc, curr) => {
const ndx = acc.findIndex((e: any) => e.group_heading === curr.group_heading);
if(ndx > -1){
acc[ndx].services.push(...curr.services)
} else{
acc.push(curr)
}
return acc;
}, [])
which outputs this as desired
[{
"group_heading": "horse",
"services": [{
"id": 0,
"name": "XyZ",
"category": [{
"title": "horse"
}, {
"title": "food"
}]
}, {
"id": 2,
"name": "something 2",
"category": [{
"title": "fishing"
}, {
"title": "horse"
}, {
"title": "food"
}]
}, {
"id": 3,
"name": "something 3",
"category": [{
"title": "horse"
}]
}]
}, {
"group_heading": "food",
"services": [{
"id": 0,
"name": "XyZ",
"category": [{
"title": "horse"
}, {
"title": "food"
}]
}, {
"id": 2,
"name": "something 2",
"category": [{
"title": "fishing"
}, {
"title": "horse"
}, {
"title": "food"
}]
}, {
"id": 4,
"name": "something 4",
"category": [{
"title": "food"
}, {
"title": "beer"
}]
}]
}, {
"group_heading": "fishing",
"services": [{
"id": 2,
"name": "something 2",
"category": [{
"title": "fishing"
}, {
"title": "horse"
}, {
"title": "food"
}]
}, {
"id": 5,
"name": "something 4",
"category": [{
"title": "fishing"
}]
}]
}, {
"group_heading": "beer",
"services": [{
"id": 4,
"name": "something 4",
"category": [{
"title": "food"
}, {
"title": "beer"
}]
}]
}]
I would probably do something like this:
// first collect services by category
const servicesByCategory = {}
for(const service of testData2){
for(const {title} of service.category){
if(!servicesByCategory[title]){
servicesByCategory[title] = []
}
servicesByCategory[title].push(data)
}
}
// whip it into whatever form you need
return Object.entries(servicesByCategory)
.map(([group_headings, services]) => ({group_headings, services}))

change one format to another format of the array of objects

I have the main three parameters that are important category, subcategory, and group
This is an array of objects and I want to change the format of this array
Like all data divide into category inside sub-category inside group wise data I want
const data =
[
{
"type": "checkbox",
"value": true,
"category": "id",
"subcategory": "id document 1",
"group": "group1"
},
{
"type": "radio",
"value": 2,
"category": "id",
"subcategory": "id document 2",
"group": "group2"
},
{
"type": "radio",
"value": 3,
"category": "id",
"subcategory": "id document 2",
"group": "group2"
},
{
"type": "string",
"value": "dfgdfg",
"category": "Services",
"subcategory": "Service A",
"group": "g1"
},
{
"type": "string",
"value": "fxs",
"category": "Services",
"subcategory": "Service A",
"group": "g1"
},
{
"type": "string",
"value": "3",
"category": "Services access",
"subcategory": "Service B",
"group": "g1"
},
{
"type": "string",
"value": "sgredfg25ghfghrt54645dfeh",
"category": "Services access",
"subcategory": "Service B",
"group": "g2"
},
{
"type": "string",
"value": "sgredfg25ghfghrt54645dfeh",
"category": "Services access",
"subcategory": "Service C",
"group": "g3"
}
]
The expected result looks like this
const data = [
{
"category": "id",
"subcategory": [
{
"subcategory_name": "id document 1",
"subcategory_data": [
{
"group": "group1",
"groupdata": [
{
"type": "checkbox",
"value": true,
"category": "id",
"subcategory": "id document 1",
"group": "group1"
}
]
}
]
},
{
"subcategory_name": "id document 2",
"subcategory_data": [
{
"group": "group1",
"groupdata": [
{
"type": "checkbox",
"value": true,
"category": "id",
"subcategory": "id document 2",
"group": "group1"
},
{
"type": "checkbox",
"value": true,
"category": "id",
"subcategory": "id document 2",
"group": "group1"
}
]
}
]
}
]
},
{
"category": "Services",
"subcategory": [
{
"subcategory_name": "Service B",
"subcategory_data": [
{
"group": "c1",
"groupdata": [
{
"type": "checkbox",
"value": true,
"category": "Services",
"subcategory": "Service B",
"group": "c1"
}
]
},
{
"group": "c2",
"groupdata": [
{
"type": "checkbox",
"value": true,
"category": "Services",
"subcategory": "Service B",
"group": "c2"
}
]
}
]
},
{
"subcategory_name": "Service C",
"subcategory_data": [
{
"group": "f1",
"groupdata": [
{
"type": "checkbox",
"value": true,
"category": "Services",
"subcategory": "Service C",
"group": "f1"
},
{
"type": "checkbox",
"value": true,
"category": "Services",
"subcategory": "Service C",
"group": "f1"
}
]
}
]
}
]
}
]
If the category match data push into the match subcategory if not then create a category for the same and if the subcategory match push into that one otherwise create a new one same as the group if the group match into subcategory then push otherwise create one
Like I want hierarchy like category => subcategory => group
And I try the this code
let finaldata = []
let flag1;
let aa = []
for (let i = 0; i < parseData.length; i++) {
if (i == 0) {
finaldata.push({ category: parseData[i].category, subcategory: [parseData[i]] })
flag1 = true
} else {
if (parseData[i - 1]?.category !== parseData[i].category) {
finaldata.push({ category: parseData[i].category, subcategory: [parseData[i]] })
} else {
aa = finaldata.map(x => x.category === parseData[i].category ? { ...x, subcategory: [...x.subcategory, parseData[i]] } : x);
}
}
if (!flag1) break;
}
does this helps?
const data =
[
{
"type": "checkbox",
"value": true,
"category": "id",
"subcategory": "id document 1",
"group": "group1"
},
{
"type": "radio",
"value": 2,
"category": "id",
"subcategory": "id document 2",
"group": "group2"
},
{
"type": "radio",
"value": 3,
"category": "id",
"subcategory": "id document 2",
"group": "group2"
},
{
"type": "string",
"value": "dfgdfg",
"category": "Services",
"subcategory": "Service A",
"group": "g1"
},
{
"type": "string",
"value": "fxs",
"category": "Services",
"subcategory": "Service A",
"group": "g1"
},
{
"type": "string",
"value": "3",
"category": "Services access",
"subcategory": "Service B",
"group": "g1"
},
{
"type": "string",
"value": "sgredfg25ghfghrt54645dfeh",
"category": "Services access",
"subcategory": "Service B",
"group": "g2"
},
{
"type": "string",
"value": "sgredfg25ghfghrt54645dfeh",
"category": "Services access",
"subcategory": "Service C",
"group": "g3"
}
]
const result = data.reduce((p, c) => {
const i = p.findIndex(p => p.category === c.category)
if (i !== -1) {
const j = p[i].subcategory.findIndex(s => s.subcategory_name === c.subcategory);
if (j !== -1) {
const k = p[i].subcategory[j].subcategory_data.findIndex(sd => sd.group === c.group);
if (k !== -1) {
p[i].subcategory[j].subcategory_data[k].groupdata.push(c);
return p;
}
p[i].subcategory[j].subcategory_data.push({
group: c.group,
groupdata: [
c
]
})
return p;
}
p[i].subcategory.push({
subcategory_name: c.subcategory,
subcategory_data: [
{
group: c.group,
groupdata: [
{
...c
}
]
}
]
})
return p
}
p.push({
category: c.category,
subcategory: [
{
subcategory_name: c.subcategory,
subcategory_data: [
{
group: c.group,
groupdata: [
c
]
}
]
}
]
})
return p;
}, []);
console.log(result);
Another approach to group items:
const data = [{"type":"checkbox","value":true,"category":"id","subcategory":"id document 1","group":"group1"},{"type":"radio","value":2,"category":"id","subcategory":"id document 2","group":"group2"},{"type":"radio","value":3,"category":"id","subcategory":"id document 2","group":"group2"},{"type":"string","value":"dfgdfg","category":"Services","subcategory":"Service A","group":"g1"},{"type":"string","value":"fxs","category":"Services","subcategory":"Service A","group":"g1"},{"type":"string","value":"3","category":"Services access","subcategory":"Service B","group":"g1"},{"type":"string","value":"sgredfg25ghfghrt54645dfeh","category":"Services access","subcategory":"Service B","group":"g2"},{"type":"string","value":"sgredfg25ghfghrt54645dfeh","category":"Services access","subcategory":"Service C","group":"g3"}];
const groupByToPairs = (items, key) => Object.entries(items.reduce((acc, item) => {
acc[item[key]] ??= [];
acc[item[key]].push(item);
return acc;
}, {}));
const makeGroups = (items) => groupByToPairs(items, 'group')
.map(([group, groupdata]) => ({ group, groupdata }));
const makeSubcategories = (items) => groupByToPairs(items, 'subcategory')
.map(([subcategory_name, items]) => ({ subcategory_name, subcategory_data: makeGroups(items) }));
const makeCategories = (items) => groupByToPairs(items, 'category')
.map(([category, items]) => ({ category, subcategory: makeSubcategories(items) }));
console.log(makeCategories(data));
.as-console-wrapper { max-height: 100% !important; top: 0 }
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.21/lodash.min.js"></script>

Javascript: Efficient way Nested Array mapping & filtering to get the desired results

I have tried the below solution for question2 to get result2. What would be a more efficient way to get both the result (result1, result2 & result3) with the same code?
question1 = [
{
"groupName": "Group 1",
"id": "group1",
"options": [
{
"name": "Cat1",
"selected": true
},
{
"name": "Cat2",
"selected": true
},
{
"name": "Cat3",
"selected": false
},
{
"name": "Cat4",
"selected": false
}
]
},
{
"groupName": "Group 2",
"id": "Brand",
"options": [
{
"name": "brand1",
"selected": false
},
{
"name": "brand2",
"selected": true
},
{
"name": "brand3",
"selected": false
}
]
},
{
"groupName": "Group 3",
"id": "Price",
"options": [
{
"name": "$0 - $9",
"selected": false
},
{
"name": "$9 - $19",
"selected": false
},
{
"name": "$20 - $29",
"selected": false
}
],
"range": {
"min": 5,
"max": 20
}
}
]
result1 = [{
"groupName": "Group 1",
"id": "group1",
"name": "Cat1",
},
{
"groupName": "Group 1",
"id": "group1",
"name": "Cat2",
},
{
"groupName": "Group 2",
"id": "Brand",
"name": "brand2",
},
{
"groupName": "Group 3",
"id": "Price",
"min": 5,
"max": 20
}
]
I have a solution for question2, although I know it's not very efficient, so what could be a better solution?
question2 = [
{
"groupName": "Group 1",
"id": "group1",
"options": [
{
"name": "Cat1",
"selected": true
},
{
"name": "Cat2",
"selected": false
},
{
"name": "Cat3",
"selected": false
},
{
"name": "Cat4",
"selected": false
}
]
},
{
"groupName": "Group 2",
"id": "Brand",
"options": [
{
"name": "brand1",
"selected": false
},
{
"name": "brand2",
"selected": true
},
{
"name": "brand3",
"selected": false
}
]
},
{
"groupName": "Group 3",
"id": "Price",
"options": [
{
"name": "$0 - $9",
"selected": true
},
{
"name": "$9 - $19",
"selected": false
},
{
"name": "$20 - $29",
"selected": false
}
],
"range": {
"min": null,
"max": null
}
}
]
const selected2 = question2.map(group => group.options.filter(option => option.selected).map(option => ({groupName: group.groupName, id: group.id, name: option.name}))).flat(1)
console.log(selected2)
For question3, group 1, none of the options is selected and correspondingly I should get result3. So, only if any of the options are selected or the price has a range (either min/max/both min&max), it is displayed in the result.
question3 = [
{
"groupName": "Group 1",
"id": "group1",
"options": [
{
"name": "Cat1",
"selected": false
},
{
"name": "Cat2",
"selected": false
},
{
"name": "Cat3",
"selected": false
},
{
"name": "Cat4",
"selected": false
}
]
},
{
"groupName": "Group 2",
"id": "Brand",
"options": [
{
"name": "brand1",
"selected": false
},
{
"name": "brand2",
"selected": true
},
{
"name": "brand3",
"selected": false
}
]
},
{
"groupName": "Group 3",
"id": "Price",
"options": [
{
"name": "$0 - $9",
"selected": false
},
{
"name": "$9 - $19",
"selected": false
},
{
"name": "$20 - $29",
"selected": false
}
],
"range": {
"min": 5,
"max": 20
}
}
]
result3 = [
{
"groupName": "Group 2",
"id": "Brand",
"name": "brand2",
},
{
"groupName": "Group 3",
"id": "Price",
"min": 5,
"max": 20
}
]
I want to use reduce to get these above (result1, result2 & result3) solutions. Could someone help me with this?
Edited to check scenario where two are selected in the same group, solution resulting in result1.
When multiple selected trues found in the accumulator object I'm adding a key where keyname is a combination of groupName and selected name. If no selected true but has max or min values the key name will be just groupName. I take Object.values() of the final object to get the array of values.
const question1 = [{"groupName": "Group 1","id": "group1","options": [{"name": "Cat1","selected": true},{"name": "Cat2","selected": true},{"name": "Cat3","selected": false},{"name": "Cat4","selected": false}]},{"groupName": "Group 2","id": "Brand","options": [{"name": "brand1","selected": false},{"name": "brand2","selected": true},{"name": "brand3","selected": false}]},{"groupName": "Group 3","id": "Price","options": [{"name": "$0 - $9","selected": false},{"name": "$9 - $19","selected": false},{"name": "$20 - $29","selected": false}],"range": {"min": 5,"max": 20}}]
const question2 = [{"groupName": "Group 1","id": "group1","options":[{"name":"Cat1","selected": true},{"name": "Cat2","selected": false},{"name":"Cat3","selected": false},{"name": "Cat4","selected": false}]},{"groupName": "Group 2","id": "Brand","options": [{"name":"brand1","selected":false},{"name": "brand2","selected": true},{"name": "brand3","selected": false}]},{"groupName": "Group 3","id": "Price","options": [{"name": "$0 -$9","selected": true},{"name": "$9 - $19","selected": false},{"name": "$20 -$29","selected": false}],"range": {"min": null,"max": null}}]
const question3 = [{"groupName": "Group 1","id": "group1","options": [{"name": "Cat1","selected": false},{"name": "Cat2","selected": false},{"name": "Cat3","selected": false},{"name": "Cat4","selected": false}]},{"groupName": "Group 2","id": "Brand","options": [{"name": "brand1","selected": false},{"name": "brand2","selected": true},{"name": "brand3","selected": false}]},{"groupName": "Group 3","id": "Price","options": [{"name": "$0 - $9","selected": false},{"name": "$9 - $19","selected": false},{"name": "$20 - $29","selected": false}],"range": {"min": 5,"max": 20}}]
const formatter = (arr) => {
return Object.values(arr.reduce((acc,curr) => {
const hasMax = curr.range && curr.range.max;
const hasMin = curr.range && curr.range.max
const filtered = curr['options'].filter((option) => option.selected);
if (filtered.length) {
filtered.forEach((el) => {
acc[curr.groupName+el.name] = {id: curr.id,groupName: curr.groupName,name: el.name}
})
}
else if (hasMin || hasMax){
acc[curr.groupName] = {id: curr.id,groupName: curr.groupName}
if(hasMax) acc[curr.groupName]['max'] = curr.range.max
if(hasMin) acc[curr.groupName]['min'] = curr.range.min
}
return acc;
},{}))
}
const result1 = formatter(question1)
const result2 = formatter(question2)
const result3 = formatter(question3)
console.log(result1)
console.log(result2)
console.log(result3)
.as-console-wrapper { max-height: 100% !important; top: 0; }

Loop Array of Object and connect them together by different keys

I'm trying to loop thru products array and find its description in description array. The product id and description parent represent the same product. If the description could be found, push the product with its description to the results array.
I don't really know how this loop should look like.
Products
let products = [
{
"id": "43",
"titel": "Phone",
"price": "211"
},{
"id": "76",
"titel": "Battery",
"price": "34"
},{
"id": "102",
"titel": "Pen",
"price": "45"
},{
"id": "127",
"titel": "Apple",
"price": "10"
}
]
Descriptions
let descriptions= [
{
"description": "Good battery",
"parent": "76"
},{
"description": "Sharp pen",
"parent": "102"
},
]
Expected output results
let results = [
{
"id": "76",
"titel": "Battery",
"price": "34"
"description": "Good battery",
"parent": "76"
},{
"id": "102",
"titel": "Pen",
"price": "45"
"description": "Sharp pen",
"parent": "102"
},
]
You can take advantage of Array.prototype.reduce which allows to transform an array to another type of Object of array.
combine with the Array.prototype.find to check if item with a given id exists in the descriptions Array
let products = [
{
"id": "43",
"titel": "Phone",
"price": "211"
},{
"id": "76",
"titel": "Battery",
"price": "34"
},{
"id": "102",
"titel": "Pen",
"price": "45"
},{
"id": "127",
"titel": "Apple",
"price": "10"
}
]
let descriptions= [
{
"description": "Good battery",
"parent": "76"
},{
"description": "Sharp pen",
"parent": "102"
},
]
const result = products.reduce((acc, item) => {
// Check if the description of the current product exists
let exist = descriptions.find(desc => {
return item.id === desc.parent;
});
if(exist) {
return acc.concat({...item, description: exist.description});
}
return acc;
}, []);
console.log(result);
If you add another array comments you can update the code instead of to concatenate the item in the accumulator directly you'll create another object which after finding the related comment in the comment array you'll add the comment key in that object with their comment.
Here is the code
let products = [
{
"id": "43",
"titel": "Phone",
"price": "211"
},{
"id": "76",
"titel": "Battery",
"price": "34"
},{
"id": "102",
"titel": "Pen",
"price": "45"
},{
"id": "127",
"titel": "Apple",
"price": "10"
}
]
let descriptions= [
{
"description": "Good battery",
"parent": "76"
},{
"description": "Sharp pen",
"parent": "102"
},
]
let comments = [
{
"comment": "Good battery comment",
"product": "76",
}, {
"comment": "Sharp pen comment",
"product": "102"
}
];
const result = products.reduce((acc, item) => {
// Check if the description of the current product exists
let productExists = descriptions.find(desc => {
return item.id === desc.parent;
});
let commentExists = comments.find(comment => {
return item.id === comment.product
});
let newItem = null;
if(productExists) {
newItem = {
...item,
description: productExists.description
};
}
if(commentExists) {
newItem.comment = commentExists.comment;
}
return newItem? acc.concat(newItem): acc;
}, []);
console.log(result);
You should iterate over the descriptions, then use there Array.find and merge them together into a new object, with Object.assign and push them to your results
let products = [
{
"id": "43",
"titel": "Phone",
"price": "211"
},{
"id": "76",
"titel": "Battery",
"price": "34"
},{
"id": "102",
"titel": "Pen",
"price": "45"
},{
"id": "127",
"titel": "Apple",
"price": "10"
}
];
let descriptions= [
{
"description": "Good battery",
"parent": "76"
},{
"description": "Sharp pen",
"parent": "102"
},
];
let results = [];
for (const desc of descriptions) {
const product = products.find(v => v.id === desc.parent);
if (!product) {
continue;
}
results.push(Object.assign({}, product, desc));
}
console.log(results);
const result = descriptions.map(descr => {
const product = products.find(prod => prod.id === descr.parent);
return {...product, ...descr}
})

javascript - Grouping elements in array by properties

I am trying to filter same color objects from the below json and every color value is containing combination of two values(color and numeric value) but I just want to filter on the basis of color.
Here what i have tried
var _ = require('underscore-plus');
var data = [{
"name": "jim",
"color": "blue 1",
"age": "22"
}, {
"name": "Sam",
"color": "blue 2",
"age": "33"
}, {
"name": "eddie",
"color": "green 1",
"age": "77"
},
{
"name": "Dheeraj",
"color": "blue 3",
"age": "25"
},
{
"name": "Suraj",
"color": "green 1",
"age": "25"
}
];
var result=_.groupBy(data,"color");
console.log(result)
Result should be array of Objects having same color.
[{ "name": "jim", "color": "blue 1", "age": "22" },
{ "name": "Sam", "color": "blue 2", "age": "33" },
{ "name": "Dheeraj", "color": "blue 3", "age": "25" }]
and
[{ "name": "Suraj", "color": "green 1", "age": "25" },
{ "name": "eddie", "color": "green 1", "age": "77" }]
You can group the items using Array.prototype.reduce:
var data = [{
"name": "jim",
"color": "blue 1",
"age": "22"
}, {
"name": "Sam",
"color": "blue 2",
"age": "33"
}, {
"name": "eddie",
"color": "green 1",
"age": "77"
}, {
"name": "Dheeraj",
"color": "blue 3",
"age": "25"
}, {
"name": "Suraj",
"color": "green 1",
"age": "25"
}];
var result = data.reduce(function(grouped, obj) {
var key = obj.color.split(' ')[0]; // get the color from the key
grouped[key] = (grouped[key] || []).concat(obj); // use the existing array or create a new array, add the object to it, and assign it to the grouped object
return grouped; // return the grouped object
}, {});
console.log(result);
You could group by the color.
var data = [{ "name": "jim", "color": "blue 1", "age": "22" }, { "name": "Sam", "color": "blue 2", "age": "33" }, { "name": "eddie", "color": "green 1", "age": "77" }, { "name": "Dheeraj", "color": "blue 3", "age": "25" }, { "name": "Suraj", "color": "green 1", "age": "25" }],
grouped = {},
colors;
data.forEach(function (a) {
var group = a.color.match(/^[a-z]+/i);
grouped[group] = grouped[group] || [];
grouped[group].push(a);
});
colors = Object.keys(grouped);
colors.forEach(function (color) {
console.log(color, grouped[color]);
});
.as-console-wrapper { max-height: 100% !important; top: 0; }
you can use Jquery.grep() for example
var result = $.grep(data, function(n){ return n.color == "blue 3" })
Simply using the groupBy function as detailed by underscore docs here:
var result = _.groupBy(data, function(datum) { return datum.color; });
You need to provide a function to be used, that will return the attribute to group the elements on, which is color in this case.
If you want to filter instead, as is mentioned in the question, you can use the underscore filter method:
var blueOne = _.filter(data, function(datum){ return datum.color == 'blue 1'; });

Categories