JavaScript count number of ocurrences in Array of Objects - javascript

I have an array of objects and I was trying to figure out how I can create a new array of objects that would display a new array of objects, but with an "occurences" field.
Here is my starting json array of objects:
const fakeJson = [
{
"Id": 1,
"Name": "John",
"Age": 32,
"Date_Available": "2022-04-10",
"Popularity": 99,
"Country": "Canada"
},
{
"Id": 1,
"Name": "John",
"Age": 32,
"Date_Available": "2022-04-11",
"Popularity": 99,
"Country": "Canada"
},
{
"Id": 1,
"Name": "John",
"Age": 32,
"Date_Available": "2022-04-12",
"Popularity": 99,
"Country": "Canada"
},
{
"Id": 1,
"Name": "John",
"Age": 32,
"Date_Available": "2022-04-12",
"Popularity": 99,
"Country": "China"
},
{
"Id": 1,
"Name": "John",
"Age": 32,
"Date_Available": "2022-04-12",
"Popularity": 99,
"Country": "Canada"
}
Example result of what I would like. Notice the for Country Canada, one of them has Occurences: 2 for Date_Available "2022-04-12". How would I be able to accomplish this?
const resultJSON = [
{
"Date_Available": "2022-04-10",
"Popularity": 99,
"Country": "Canada",
"Occurrences" : 1
},
{
"Date_Available": "2022-04-11",
"Popularity": 99,
"Country": "Canada",
"Ocurrences" : 1
},
{
"Date_Available": "2022-04-12",
"Popularity": 99,
"Country": "Canada",
"Occurrences" : 2
},
{
"Date_Available": "2022-04-12",
"Popularity": 99,
"Country": "China",
"Occurrences" : 1
}
Here is what I have so far. My idea was to create a temporary obj with the country name, date available and occurrence set default to 1. Then based on the Date_Available, increase by 1 every time it appeared. However, if China and Canada both have the same date, then it seems to mess up the code and does not properly print the result.
let countNameMapping = {};
let finalArr = [];
for(let i = 0; i < fakeJson.length; i++){
let tempObj = {Country:fakeJson[i].Country, Date_Available: fakeJson[i].Date_Available, occurence: 1};
let countryName = fakeJson[i].Country;
let date = fakeJson[i].Date_Available;
if(countNameMapping[date] === undefined){
countNameMapping[countryName] = tempObj;
} else {
countNameMapping[date].occurence += 1;
}
}
for(let k in countNameMapping){
finalArr.push(countNameMapping[k])
}
console.log(finalArr)

const json = fakeJson.reduce((prev, curr) => {
const check = () => prev.findIndex(({ Date_Available, Country }) =>
curr.Date_Available === Date_Available &&
curr.Country === Country
);
check() === -1
? prev.push({
...Object.fromEntries(
Object.entries(curr).filter(([key]) => !key.match(/id|name|age/i))
),
Occurences: 1 })
: prev[check()].Occurences++
return prev
}, [])
console.log({ json });

Group by a custom key, eg Date_Available + Country
reduce() the result, create an array with the first object as base, then add Ocurrences, based on the amount of objects found (.length)
const data = [{"Id": 1, "Name": "John", "Age": 32, "Date_Available": "2022-04-10", "Popularity": 99, "Country": "Canada"}, {"Id": 1, "Name": "John", "Age": 32, "Date_Available": "2022-04-11", "Popularity": 99, "Country": "Canada"}, {"Id": 1, "Name": "John", "Age": 32, "Date_Available": "2022-04-12", "Popularity": 99, "Country": "Canada"}, {"Id": 1, "Name": "John", "Age": 32, "Date_Available": "2022-04-12", "Popularity": 99, "Country": "China"}, {"Id": 1, "Name": "John", "Age": 32, "Date_Available": "2022-04-12", "Popularity": 99, "Country": "Canada"}];
const grouped = data.reduce((p, c) => {
const key = c.Date_Available + c.Country;
(p[key] = p[key] || []).push(c);
return p;
}, {});
const result = Object.values(grouped).reduce((p, c) => [ ...p, { ...c[0], Ocurrences: c.length } ], []);
console.log(result)
Result:
[
{
"Id": 1,
"Name": "John",
"Age": 32,
"Date_Available": "2022-04-10",
"Popularity": 99,
"Country": "Canada",
"Ocurrences": 1
},
{
"Id": 1,
"Name": "John",
"Age": 32,
"Date_Available": "2022-04-11",
"Popularity": 99,
"Country": "Canada",
"Ocurrences": 1
},
{
"Id": 1,
"Name": "John",
"Age": 32,
"Date_Available": "2022-04-12",
"Popularity": 99,
"Country": "Canada",
"Ocurrences": 2
},
{
"Id": 1,
"Name": "John",
"Age": 32,
"Date_Available": "2022-04-12",
"Popularity": 99,
"Country": "China",
"Ocurrences": 1
}
]

you can use reduce and Object.values for that
like this
const groupBy = (data, ...keyGroup) => Object.values(data.reduce((res, item) => {
const key = keyGroup.map(k => item[k]).join('-')
const existing = res[key] || {...item, occurencies: 0}
return {
...res,
[key]: {...existing,occurencies: existing.occurencies + 1 }
}
}, {}))
const fakeJson = [
{
"Id": 1,
"Name": "John",
"Age": 32,
"Date_Available": "2022-04-10",
"Popularity": 99,
"Country": "Canada"
},
{
"Id": 1,
"Name": "John",
"Age": 32,
"Date_Available": "2022-04-11",
"Popularity": 99,
"Country": "Canada"
},
{
"Id": 1,
"Name": "John",
"Age": 32,
"Date_Available": "2022-04-12",
"Popularity": 99,
"Country": "Canada"
},
{
"Id": 1,
"Name": "John",
"Age": 32,
"Date_Available": "2022-04-12",
"Popularity": 99,
"Country": "China"
},
{
"Id": 1,
"Name": "John",
"Age": 32,
"Date_Available": "2022-04-12",
"Popularity": 99,
"Country": "Canada"
}
]
console.log('by ID', groupBy(fakeJson, 'Id'))
console.log('by Country', groupBy(fakeJson, 'Country'))
console.log('by country and date', groupBy( fakeJson, 'Country', 'Date_Available'))

Related

setting object key dynamically in javascript

I have an object like this:
let inputData = {
"dimensions": [
{
"id": "dimension_re",
"label": "Region",
"values": ["East", "East", "West", "SouthWest", "South","NorthEast"]
},
{
"id": "dimension_cnt",
"label": "County",
"values": ["London", "Italy", "Germany", "US", "Russia","India"]
},
{
"id": "measure_sales",
"label": "Sales",
"values": [100, 156, 432, 462, 25,100]
},
{
"id": "measure_qty",
"label": "Quantity",
"values": [85, 34, 153, 434, 52, 43]
},
{
"id": "measure_profit",
"label": "Profit",
"values": [123, 45, 421, 465, 451, 56]
}
]
}
My expected output:
let expectdData = [
{
"Region": "East",
"County": "London",
"Sales": 100,
"Quantity": 85,
"Profit": 123
},
{
"Region": "East",
"County": "Italy",
"Sales": 156,
"Quantity": 34,
"Profit": 45
},
{
"Region": "West",
"County": "Germany",
"Sales": 432,
"Quantity": 153,
"Profit": 421
},
{
"Region": "SouthWest",
"County": "US",
"Sales": 462,
"Quantity": 434,
"Profit": 465
},
{
"Region": "South",
"County": "Russia",
"Sales": 25,
"Quantity": 52,
"Profit": 451
},
{
"Region": "NorthEast",
"County": "India",
"Sales": 100,
"Quantity": 43,
"Profit": 56
}
]
Here is my program to get this expected data:
let actualData = [];
inputData.dimensions.forEach((e,i) => {
let tempVal = e.label;
e.values.forEach((elem,index) => {
actualData[index] = new Object({
[tempVal] : elem
});
})
});
console.log(actualData);
But unfortunately, I only get the last item for every object. In my console it looks like this:
[
{ Profit: 123 },
{ Profit: 45 },
{ Profit: 421 },
{ Profit: 465 },
{ Profit: 451 },
{ Profit: 56 }
]
I think, in every iteration, it just overrides the "tempVal" variable. How to prevent this & how can I achieve the expected array of objects?
You are replacing the whole object on each iteration, you just need to create it if it does not exists, otherwise you can replace the key.
let actualData = [];
inputData.dimensions.forEach((e,i)=>{
let tempVal = e.label;
e.values.forEach((elem,index) => {
if (!actualData[index]) {
actualData[index] = {}
}
actualData[index][tempVal] = elem
})
});
console.log(actualData);
Using Array#reduce, iterate over dimension while updating a list of the resulting objects
In each iteration, use Array#forEach to iterate over the current values list and update the object at each index with label as key and the current value as value
const inputData = {
"dimensions": [
{
"id": "dimension_re",
"label": "Region",
"values": ["East", "East", "West", "SouthWest", "South","NorthEast"]
},
{
"id": "dimension_cnt",
"label": "County",
"values": ["London", "Italy", "Germany", "US", "Russia","India"]
},
{
"id": "measure_sales",
"label": "Sales",
"values": [100, 156, 432, 462, 25,100]
},
{
"id": "measure_qty",
"label": "Quantity",
"values": [85, 34, 153, 434, 52, 43]
},
{
"id": "measure_profit",
"label": "Profit",
"values": [123, 45, 421, 465, 451, 56]
}
]
};
const res = inputData.dimensions.reduce((acc, { label, values = [] }) => {
values.forEach((value, index) => {
acc[index] = { ...(acc[index] ?? {}), [label]: value };
});
return acc;
}, []);
console.log(res);
Since your index comes from the inner loop, you'll be replacing the values at actualData[index] each outer loop iteration, that's why you only end up with the last.
Try this reduce operation instead...
const inputData = {"dimensions":[{"id":"dimension_re","label":"Region","values":["East","East","West","SouthWest","South","NorthEast"]},{"id":"dimension_cnt","label":"County","values":["London","Italy","Germany","US","Russia","India"]},{"id":"measure_sales","label":"Sales","values":[100,156,432,462,25,100]},{"id":"measure_qty","label":"Quantity","values":[85,34,153,434,52,43]},{"id":"measure_profit","label":"Profit","values":[123,45,421,465,451,56]}]};
// Find the max number of `values`
const maxLength = Math.max(...inputData.dimensions.map(({ values }) => values.length));
const actualData = inputData.dimensions.reduce(
(arr, { label, values }) =>
arr.map((obj, i) => ({ ...obj, [label]: values[i] })),
Array.from(
{
length: maxLength,
},
() => ({}) // creates an array of empty objects
)
);
console.log(actualData);
.as-console-wrapper { max-height: 100% !important; }

Convert an object to 3d array

I am new to node.js and javascript. I am trying to build a rest API.
For a specific purpose, I need to convert an object to 3d array.
I tried running for, foreach loop but it is not providing what I am trying to achieve.
My object looks like this.
"data": [
{
"id": 15184,
"badge_id": "330886",
"name": "Rukmani J. Solanki",
"gender": "Female",
"type": "PF",
"department": "Sales",
"checkin": "2021-09-24T08:52:44.000Z",
"checkout": "2021-09-24T08:57:45.000Z",
"hours": "00:05"
},
{
"id": 15185,
"badge_id": "440886",
"name": "Jairam J. Solanki",
"gender": "Male",
"type": "PM",
"department": "Sales",
"checkin": "2021-09-24T09:28:32.000Z",
"checkout": null,
"hours": null
}
]
And I want something like this
{
"onfield": [
{
"key": "Sales",
"data": {
"PM": [
{
"name": "Gokuldas S. Sundrani",
"badge_id": "441101",
"gender": "Male",
"checkIn": "2021-09-24 06:04:18",
"checkOut": null,
"hours": "NoCheckOut"
},
{
"name": "Satnamsingh M. Chhabra",
"badge_id": "551249",
"gender": "Male",
"checkIn": "2021-09-24 06:47:31",
"checkOut": "2021-09-24 08:32:00",
"hours": "1.7 Hours"
},
{
"name": "Praveen N. Jethwani",
"badge_id": "771328",
"gender": "Male",
"checkIn": "2021-09-24 07:14:11",
"checkOut": "2021-09-24 08:29:34",
"hours": "1.3 Hours"
},
{
"name": "Satnamsingh M. Chhabra",
"badge_id": "88249",
"gender": "Male",
"checkIn": "2021-09-24 08:32:00",
"checkOut": null,
"hours": "NoCheckOut"
},
{
"name": "Arjundas D. Chhabra",
"badge_id": "661248",
"gender": "Male",
"checkIn": "2021-09-24 10:19:22",
"checkOut": "2021-09-24 18:38:32",
"hours": "8.3 Hours"
},
{
"name": "Parmanand C. Lalwani",
"badge_id": "8651418",
"gender": "Male",
"checkIn": "2021-09-24 14:51:08",
"checkOut": "2021-09-24 17:39:27",
"hours": "2.8 Hours"
},
{
"name": "Dhanalal G. Chouhan",
"badge_id": "5501392",
"gender": "Male",
"checkIn": "2021-09-24 14:58:46",
"checkOut": "2021-09-24 18:20:50",
"hours": "3.4 Hours"
}
],
"PF": [
{
"name": "Baljeetkaur S. Chhabra",
"badge_id": "501993",
"gender": "Female",
"checkIn": "2021-09-24 06:47:48",
"checkOut": "2021-09-24 08:32:12",
"hours": "1.7 Hours"
},
{
"name": "Baljeetkaur S. Chhabra",
"badge_id": "801993",
"gender": "Female",
"checkIn": "2021-09-24 08:32:12",
"checkOut": null,
"hours": "NoCheckOut"
}
],
"OM": [
{
"name": "Yadvendra Bhati",
"badge_id": "2255454",
"gender": "male",
"checkIn": "2021-09-24 13:38:37",
"checkOut": "2021-09-24 17:24:11",
"hours": "3.8 Hours"
}
],
"OF": [
{
"name": "Yashoda Bhati",
"badge_id": "223F0029",
"gender": "Female",
"checkIn": "2021-09-24 13:38:44",
"checkOut": "2021-09-24 17:24:25",
"hours": "3.8 Hours"
}
]
}
}
]
}
How can this be done?
I will be really grateful to you for your help.
I have googled and searched StackOverflow but did not find anything which deals with this kind of problem.
Thank You
Although I totally agree with Juan Mendes, here is a tip in order for you to be able to accomplish this. You may get an intermediate form for your data as this one:
{
"onfield": [
{
"key": "dept1",
"data": {
"PM": [
{
"id": 123,
"badge_id": "1231",
"name": "name1",
"gender": "Male"
}
]
}
},
{
"key": "dept2",
"data": {
"PF": [
{
"id": 124,
"badge_id": "1232",
"name": "name2",
"gender": "Female"
}
]
}
},
{
"key": "dept1",
"data": {
"PM": [
{
"id": 125,
"badge_id": "1233",
"name": "name3",
"gender": "Male",
"type": "PM",
"dept": "dept1"
}
]
}
}
]
}
Perhaps transforming your source data to this one is easier. And getting to your target from here will be just a matter of merging arrays of the same type.
Do not hesitate to ask if this keeps being difficult. But as said, please try to solve this yourself, that's the way you are going to learn.
let data = [{ "id": 123, "badge_id": "1231", "name": "name1", "gender": "Male", "type": "PM", "dept": "dept1" }, { "id": 124, "badge_id": "1232", "name": "name2", "gender": "Female", "type": "PF", "dept": "dept2" }, { "id": 125, "badge_id": "1233", "name": "name3", "gender": "Male", "type": "PM", "dept": "dept1" }];
let Report = []
data.forEach((item) => {
let obj = Report.find(v => v.dept == item.dept);
if (!obj) Report.push(obj = {
dept: item.dept,
type: {}
});
obj.type[item.type] ??= [];
obj.type[item.type].push({
id: item.id,
badge_id: item.badge_id,
name: item.name,
gender: item.gender,
});
})
console.log(Report)
Here's Something i think is more feasible than your result .. Checkout
let myObject = {
"data": [ {
"id": 123,
"badge_id": "1231",
"name": "name1",
"gender": "Male",
"type": "PM",
"dept": "dept1"
},
{
"id": 124,
"badge_id": "1232",
"name": "name2",
"gender": "Female",
"type": "PF",
"dept": "dept2"
},
{
"id": 125,
"badge_id": "1233",
"name": "name3",
"gender": "Male",
"type": "PM",
"dept": "dept1"
}]
}
function generateReport(object) {
let obj = {
"Report": []
};
let types = [];
object.data.forEach(arr =>{
if(!types.includes(arr.type)){
types.push(arr.type);
}
});
types.forEach(type =>{
obj.Report.push({
type : type,
users : object.data.filter(arr=>{ let a = arr.type == type;
if(a){
delete arr.type;
}
return a;
})
});
});
return obj;
}
myObject = generateReport(myObject);
console.log(myObject)
You oculd take the wanted grouping keys in an array and destructure the object to remove this keys from the object.
Every key takes it own nested object structure.
const
data = [{ id: 123, badge_id: "1231", name: "name1", gender: "Male", type: "PM", dept: "dept1" }, { id: 124, badge_id: "1232", name: "name2", gender: "Female", type: "PF", dept: "dept2" }, { id: 125, badge_id: "1233", name: "name3", gender: "Male", type: "PM", dept: "dept1" }],
keys = ['dept', 'type'],
result = data
.reduce((r, o) => {
keys
.reduce(function (t, k) {
let key;
({ [k]: key, ...o } = o);
if (!t[key]) t._.push({ [k]: key, data: (t[key] = { _: [] })._ });
return t[key];
}, r)
._
.push(o);
return r;
}, { _: [] })
._;
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

How do I remove properties from JavaScript object in array?

Let say I have this array as follows:
[
{
"id": 111,
"productName": "Chicken",
"variant": 9,
"variantName": "small",
"extrasSelected": [],
"price": 26,
"qty": "1"
},
{
"id": 112,
"productName": "Fish",
"variant": 25,
"variantName": "small",
"extrasSelected": [],
"price": 26,
"qty": "1"
}
]
How do I remove some of the properties so it will end up as follows?
[
{
"id": 111,
"variant": 9,
"extrasSelected": [],
"qty": "1"
},
{
"id": 112,
"variant": 25,
"extrasSelected": [],
"qty": "1"
}
]
The reasons why I need to do so, because I need to send the newObject data into my finalCart, but I need the productName in oldObject to display it on my view.
Just do a destructuring inside a .map
const data = [
{
"id": 111,
"productName": "Chicken",
"variant": 9,
"variantName": "small",
"extrasSelected": [],
"price": 26,
"qty": "1"
},
{
"id": 112,
"productName": "Fish",
"variant": 25,
"variantName": "small",
"extrasSelected": [],
"price": 26,
"qty": "1"
}
];
// 1
const result = data.map(({ id, variant, extrasSelected, qty }) => ({
id,
variant,
extrasSelected,
qty
}));
// Detailed explanation
// 2
// 2 is same as 1
const result2 = data.map((item => {
const { id, variant, extrasSelected, qty } = item;
return { id, variant, extrasSelected, qty };
}));
// 3
// 3 is same as 2
const result3 = data.map((item) => {
const id = item.id;
const variant = item.variant;
const extrasSelected = item.extrasSelected;
const qty = item.qty;
return {
id: id,
variant: variant,
extrasSelected: extrasSelected,
qty: qty
}
});
console.log(result);
/*
[
{ id: 111, variant: 9, extrasSelected: [], qty: '1' },
{ id: 112, variant: 25, extrasSelected: [], qty: '1' }
]
*/
You can use Array.prototype.map
[
{
"id": 111,
"productName": "Chicken",
"variant": 9,
"variantName": "small",
"extrasSelected": [],
"price": 26,
"qty": "1"
},
{
"id": 112,
"productName": "Fish",
"variant": 25,
"variantName": "small",
"extrasSelected": [],
"price": 26,
"qty": "1"
}
].map(({id, variant, extrasSelected, qty}) => ({id, variant, extrasSelected, qty}))
Variation on the above solutions. Use Array.Map and rest parameters.
const data = [{
"id": 111,
"productName": "Chicken",
"variant": 9,
"variantName": "small",
"extrasSelected": [],
"price": 26,
"qty": "1"
},
{
"id": 112,
"productName": "Fish",
"variant": 25,
"variantName": "small",
"extrasSelected": [],
"price": 26,
"qty": "1"
}
]
const result = data.map(({
productName,
variantName,
...rest
}) => rest);
console.log(JSON.stringify(result, null, 4));
There are many ways to do this.
If you actually want to delete the properties, here is one way:
let array = [
{
"id": 111,
"productName": "Chicken",
"variant": 9,
"variantName": "small",
"extrasSelected": [],
"price": 26,
"qty": "1"
},
{
"id": 112,
"productName": "Fish",
"variant": 25,
"variantName": "small",
"extrasSelected": [],
"price": 26,
"qty": "1"
}
]
array.forEach(obj => {
delete obj.variantName;
delete obj.price;
delete obj.productName;
});
console.log(array);

Add a property to grouped objects and ungroup

I'm using underscore.js to group my objects, now I want to add a property to work as an identifier for that group and then reduce those objects back into its original structure. But not sure how to do it.
The rule is to find who has more than one appointment in that day and add a property to it.
Something we achieved here:
https://jsfiddle.net/bjxgszmw/
with this line of code:
var resultt = _.chain(allAppointments)
.groupBy('appointment_date')
.mapObject( date => _.groupBy(date, 'email' ) )
So from what we have've got which is this:
{
"23July": {
"john#domain.com": [
{
"ap_id": 23,
"name": "John",
"email": "john#domain.com",
"appointment_date": "23July",
"appointment_category": 3,
"time": "morning"
},
{
"ap_id": 44,
"name": "John",
"email": "john#domain.com",
"appointment_date": "23July",
"appointment_category": 4,
"time": "afternon"
}
],
"rose#domain.com": [
{
"ap_id": 55,
to something simple like this;
allAppointments_Filtered:
[{
"ap_id": 23,
"name": "John",
"email": "John#domain.com",
"appointment_date": "23July",
"appointment_category": 3,
"time": "morning",
hasMultipleAppointmentOnDate: "yes"
},{
"ap_id": 55,
"name": "Rose",
"email": "rose#domain.com",
"appointment_date": "23July",
"appointment_category": 4,
"time": "afternoon"
hasMultipleAppointmentOnDate: "nope"
},{
"ap_id": 44,
"name": "John",
"email": "john#domain.com",
"appointment_date": "23July",
"appointment_category": 4,
"time": "afternoon"
hasMultipleAppointmentOnDate: "yes"
},{
...
}];
Well, you don't need to do all those grouping and mappings. All you have to do is a single map and a count based on the current appointment you check:
var allAppointments = [
{
"ap_id": 23,
"name": "John",
"email": "john#domain.com",
"appointment_date": "23July",
"appointment_category": 3,
"time": "morning"
},
{
"ap_id": 55,
"name": "Rose",
"email": "rose#domain.com",
"appointment_date": "23July",
"appointment_category": 4,
"time": "afternon"
},
{
"ap_id": 44,
"name": "John",
"email": "john#domain.com",
"appointment_date": "23July",
"appointment_category": 4,
"time": "afternon"
},
{
"ap_id": 70,
"name": "Kate",
"email": "kate#domain.com",
"appointment_date": "29July",
"appointment_category": 4,
"time": "afternon"
}
]
var counts = {};
var result = _.mapObject(allAppointments, (appointment) => {
var key = appointment.email + appointment.appointment_date;
if (!_.has(counts, key)) {
counts[key] = _.countBy(allAppointments, (app) =>
appointment.email === app.email &&
appointment.appointment_date === app.appointment_date
).true > 1
}
appointment.hasMultipleAppointmentOnDate = counts[key];
return appointment;
});
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
You need to group by a composite key:
// data
const allAppointments = [
{
"ap_id": 23,
"name": "John",
"email": "john#domain.com",
"appointment_date": "23July",
"appointment_category": 3,
"time": "morning"
},
{
"ap_id": 55,
"name": "Rose",
"email": "rose#domain.com",
"appointment_date": "23July",
"appointment_category": 4,
"time": "afternon"
},
{
"ap_id": 44,
"name": "John",
"email": "john#domain.com",
"appointment_date": "23July",
"appointment_category": 4,
"time": "afternon"
},
{
"ap_id": 70,
"name": "Kate",
"email": "kate#domain.com",
"appointment_date": "29July",
"appointment_category": 4,
"time": "afternon"
}
];
// gets grouping key, which is email + date
const groupKey = i => i.email +'_'+ i.appointment_date;
// store counts for appointments for unique (email + date)
const counts = _.countBy(allAppointments,groupKey);
// checks if appointment has more than one instances on date
const isMulti = i => counts[groupKey(i)] > 1;
// updated appointment with multiple indicator property
const multiProp = i => ({hasMultipleAppointmentOnDate: isMulti(i) ? "yes": "nope"});
// update initial array items with multiple
const updated = _.map(allAppointments,i => _.extend(i,multiProp(i)));
// see results
console.log(updated);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>

underscore.js how to combine 2 collections

I have two collections A and B. ( A,B have the exactly same structure, but different nodes values)
now I'd like to add A into B, with exactly the order: A B and without merging or changing any
nodes inside them. ( just like a joint action) { A } + {B}
I've read the documentation for underscore but couldn't find a proper function which gets this job done.
any idea?
==========update with example ========Sample is simplified from a larger structure, if there are errors please let me know=========
var collection1 = [{
"date": "29 January 2014",
"items": [{
"name": "Jack",
"score": 90,
"title": "programmer"
}, {
"name": "TOM",
"score": 52,
"title": "designer"
}]
}, {
"date": "28 January 2014",
"items": [{
"name": "Jim",
"score": 30,
"title": "driver"
}, {
"name": "William",
"score": 52,
"title": "worker"
}]
}]
var collect2 = [{
"date": "26 January 2014",
"items": [{
"name": "Marry",
"score": 92,
"title": "teacher"
}, {
"name": "TOM",
"score": 52,
"title": "designer"
}]
}]
========expected output==============
[{
"date": "29 January 2014",
"items": [{
"name": "Jack",
"score": 90,
"title": "programmer"
}, {
"name": "TOM",
"score": 52,
"title": "designer"
}]
}, {
"date": "28 January 2014",
"items": [{
"name": "Jim",
"score": 30,
"title": "driver"
}, {
"name": "William",
"score": 52,
"title": "worker"
}]
}, {
"date": "26 January 2014",
"items": [{
"name": "Marry",
"score": 92,
"title": "teacher"
}, {
"name": "TOM",
"score": 52,
"title": "designer"
}]
}]
I think what you are looking for is simply Array.concat
var foo = ['a','b','c'];
var bar = ['d','e','f'];
var all = foo.concat(bar); // ['a','b','c','d','e','f'];
Use Underscore#extend as : _.extend(collection1, collection2);
DEMO
col1 = { aa: 'aa', cc: 'cc' }; col2 = { bb: 'bb', dd: 'dd' };
_.extend(col1, col2)
console.log(col1);
# Prints Object {aa: "aa", cc: "cc", bb: "bb", dd: "dd"}

Categories