I have two array Applications and ApplicationOrder with below data. I want to sort the data in Applications based on Order value from ApplicationOrder Array, Where order number are repeating then we need to sort on Title field from Applications.ID field is common in both sets of data.
Applications =
[ {
"ID": 30,
"Title": "Balance",
"Acronym": null,
"Link": {
"$2_1": "https:abc.com",
"$1_1": "https:abc.com"
}
},
{
"ID": 12,
"Title": "Scorecard",
"Acronym": null,
"Link": {
"$2_1": "https:xyz.com",
"$1_1": "https:xyz.com"
}
},
{
"ID": 62,
"Title": "Best Practices",
"Acronym": null,
"Link": {
"$2_1": "https:xyz.com",
"$1_1": "https:xyz.com"
}
},
{
"ID": 15,
"Title": "User Actions",
"Acronym": null,
"Link": {
"$2_1": "https:xyz.com",
"$1_1": "https:xyz.com"
},
}];
ApplicationOrder = [{"Id":"30","Order":"4"},{"Id":"12","Order":"4"},{"Id":"62","Order":"2"},{"Id":"15","Order":"1"}];
First sort based on the order:
User Actions - Order 1
Best Practices - Order 2
Scorecard - Order 4
Balance - Order 4
Sort second time based on title since two numbers have same order
User Actions - Order 1
Best Practices - Order 2
Balance - Order 4
Scorecard - Order 4
Output should be as follows:
Applications =
[ {
"ID": 15,
"Title": "User Actions",
"Acronym": null,
"Link": {
"$2_1": "https:xyz.com",
"$1_1": "https:xyz.com"
},
},
{
"ID": 62,
"Title": "Best Practices",
"Acronym": null,
"Link": {
"$2_1": "https:xyz.com",
"$1_1": "https:xyz.com"
}
},
{
"ID": 30,
"Title": "Balance",
"Acronym": null,
"Link": {
"$2_1": "https:abc.com",
"$1_1": "https:abc.com"
}
},
{
"ID": 12,
"Title": "Scorecard",
"Acronym": null,
"Link": {
"$2_1": "https:xyz.com",
"$1_1": "https:xyz.com"
}
}];
Thank you in advance for your help.
You could use reduce() and sort() methods to achieve this:
const Applications = [
{
ID: 30,
Title: "Balance",
Acronym: null,
Link: {
"$2_1": "https:abc.com",
"$1_1": "https:abc.com"
}
},
{
ID: 12,
Title: "Scorecard",
Acronym: null,
Link: {
"$2_1": "https:xyz.com",
"$1_1": "https:xyz.com"
}
},
{
ID: 62,
Title: "Best Practices",
Acronym: null,
Link: {
"$2_1": "https:xyz.com",
"$1_1": "https:xyz.com"
}
},
{
ID: 15,
Title: "User Actions",
Acronym: null,
Link: {
"$2_1": "https:xyz.com",
"$1_1": "https:xyz.com"
},
}
];
const ApplicationOrder = [
{"Id":"30","Order":"4"},
{"Id":"12","Order":"4"},
{"Id":"62","Order":"2"},
{"Id":"15","Order":"1"}
];
// Function to sort the data in Applications based on Order value from ApplicationOrder Array
const orderMap = ApplicationOrder.reduce((acc, item) => {
// Create a map of the order values keyed by ID
acc[item.Id] = item.Order;
return acc;
}, {});
Applications.sort((a, b) => {
// Get the order values for each application based on the map
const aOrder = orderMap[a.ID];
const bOrder = orderMap[b.ID];
if (aOrder !== bOrder) {
// If the order values are different, sort based on order value
return aOrder - bOrder;
} else {
// If the order values are the same, sort based on the Title field
return a.Title.localeCompare(b.Title);
}
});
console.log(Applications);
You could get an object and sort woth value.
const
applications = [{ ID: 30, Title: "Balance", Acronym: null, Link: { $2_1: "https:abc.com", $1_1: "https:abc.com" } }, { ID: 12, Title: "Scorecard", Acronym: null, Link: { $2_1: "https:xyz.com", $1_1: "https:xyz.com" } }, { ID: 62, Title: "Best Practices", Acronym: null, Link: { $2_1: "https:xyz.com", $1_1: "https:xyz.com" } }, { ID: 15, Title: "User Actions", Acronym: null, Link: { $2_1: "https:xyz.com", $1_1: "https:xyz.com" } }],
applicationOrder = [{ Id: "30", Order: "4" }, { Id: "12", Order: "4" }, { Id: "62", Order: "2" }, { Id: "15", Order: "1" }],
order = Object.fromEntries(applicationOrder.map(({ Id, Order }) => [Id, Order]));
applications.sort((a, b) =>
order[a.ID] - order[b.ID] ||
a.Title.localeCompare(b.Title)
);
console.log(applications);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Related
I would like to get the summed value of all the arrays in the "products" object (price * quantity). The summed value should be returned in the return.
Do you have any ideas how to do that?
{
"event": "checkout",
"ecommerce": {
"checkout": {
"actionField": {
"step": 2,
"option": "Initiate checkout",
"action": "checkout"
},
"products": [
{
"id": "52",
"name": "Turystyczna kuchenka gazowa SMILE-KN-03/1K",
"price": 161.788618,
"brand": "",
"category": "kuchenki-elektryczne-i-gazowe",
"variant": "",
"quantity": "1"
},
{
"id": "36",
"name": "Kuchnia gazowa MPM-51-KGF-21",
"price": 641.463415,
"brand": "",
"category": "kuchnie-gazowe",
"variant": "",
"quantity": "1"
}
]
}
},
"gtm.uniqueEventId": 12
}
const g = {
event: 'checkout',
ecommerce: {
checkout: {
actionField: {
step: 2,
option: 'Initiate checkout',
action: 'checkout',
},
products: [
{
id: '52',
name: 'Turystyczna kuchenka gazowa SMILE-KN-03/1K',
price: 161.788618,
brand: '',
category: 'kuchenki-elektryczne-i-gazowe',
variant: '',
quantity: '1',
},
{
id: '36',
name: 'Kuchnia gazowa MPM-51-KGF-21',
price: 641.463415,
brand: '',
category: 'kuchnie-gazowe',
variant: '',
quantity: '1',
},
],
},
},
'gtm.uniqueEventId': 12,
};
const c = g.ecommerce.checkout.products.reduce((acc, curr) => {
acc += curr.price * curr.quantity;
return acc;
}, 0);
console.log(c)
guess you want something like this?
I have an array of objects called employees. I need a solution that will return me a list of groups and respective employees present in the group along with the group properties.
The example is below, I have used an object but the result can also be an array that has a property called groupName within an object. [{groupName:"developer", employees:[],...}..] As long as the response returns a list of groups with their corresponding employees.
Below is the solution I did but I need a solution with a better time complexity that is O(n).
const employees = [
{ "name": "John Doe",
"id": "1",
"groups": [
{ "id": "developerId", "name": "developer", "color": "#fff" },
{ "id": "engineerId", "name": "engineer", "color": "#fff" }
],
"groupId":["developerId", "engineerId"]
},
{ "name": "Jane Doe",
"id": "2",
"groups": [
{ "id": "developerId", "name": "developer", "color": "#fff" },
{ "id": "testerId", "name": "tester", "color": "#fff" }
],
"groupId":["developerId", "testerId"]
}
]
//Solution O(m*n)
let groups = {};
employees.forEach((item) => {
item.groups.forEach((group) => {
if (!groups[group.name]) {
groups[group.name] = {
employees: [item.id],
...group,
};
} else {
groups[group.name].employees = [...groups[group.name].employees, item.id];
}
});
});
//result
{
"developer":{
"id":"developerId",
"employee":[
"1",
"2"
],
"color":"#fff"
},
"engineer":{
"id":"employeeId",
"employee":[
"1",
],
"color":"#fff"
},
"tester":{
"id":"testerId",
"employee":[
"2",
],
"color":"#fff"
}
}
Using Array#reduce and Array#forEach:
const employees = [
{
"name": "John Doe",
"id": "1",
"groups": [
{ "id": "developerId", "name": "developer", "color": "#fff" },
{ "id": "engineerId", "name": "engineer", "color": "#fff" }
],
"groupId": ["developerId", "engineerId"]
},
{
"name": "Jane Doe",
"id": "2",
"groups": [
{ "id": "developerId", "name": "developer", "color": "#fff" },
{ "id": "testerId", "name": "tester", "color": "#fff" }
],
"groupId": ["developerId", "testerId"]
}
];
const groups = employees.reduce((acc, { id: employeeId, groups = [] }) => {
groups.forEach(({ id, name, color }) => {
acc[name] = {
id, color, employee: [...(acc[name]?.employee ?? []), employeeId]
};
});
return acc;
}, {});
console.log(groups);
If you like to add some speed, you could use the old fashioned for statement for iterating, especially of having only a single result object.
This approach does not create an object again and again and uses the already existing objects.
const
employees = [{ name: "John Doe", id: "1", groups: [{ id: "developerId", name: "developer", color: "#fff" }, { id: "engineerId", name: "engineer", color: "#fff" }], groupId: ["developerId", "engineerId"] }, { name: "Jane Doe", id: "2", groups: [{ id: "developerId", name: "developer", color: "#fff" }, { id: "testerId", name: "tester", color: "#fff" }], groupId: ["developerId", "testerId"] }],
result = {};
for (const { id: employeeId, groups } of employees) {
for (const { id, name, color } of groups) {
result[name] ??= { id, color, employee: [] };
result[name].employee.push(employeeId);
}
}
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I am trying to get the value of "type" from the object by iterating over it. The object looks like this.
{
"team": {
"table": [
{
"cityCode": 123,
"list": {
"players": [
{
"name": "peter",
"school": "x",
"awards": {
"type": "gold"
},
"year": 2019
}
]
}
},
{
"cityCode": 456,
"list": {
"players": [
{
"name": "Dave",
"school": "y",
"awards": {
"type": "silver"
},
"year": 2018
}
]
}
}
]
}
}
I am able to get the type values using this:
const table = team.table;
for (let i = 0; i < table.length; i++) {
const values = {
type: table[i].list.players
.filter((a) => a.awards != null)
.map((a) => a.awards.type)
.join(" "),
};
}
However, I want to use another filter on the "list" to filter non null lists. So how can I achieve that.
You want to check Check if 'list' key exists inside a team.table JSON object
you can check by
if(table[i].hasOwnProperty('list')){
}
code is
const table = team.table;
for (let i = 0; i < table.length; i++) {
if(table[i].hasOwnProperty('list')){
const values = {
type: table[i].list.players
.filter((a) => a.awards != null)
.map((a) => a.awards.type)
.join(" "),
};
}
}
1) You can get all type using flatMap and map as:
obj.team.table.flatMap((o) => o.list.players.map((o) => o.awards.type))
const obj = {
team: {
table: [
{
cityCode: 123,
list: {
players: [
{
name: "peter",
school: "x",
awards: {
type: "gold",
},
year: 2019,
},
],
},
},
{
cityCode: 456,
list: {
players: [
{
name: "Dave",
school: "y",
awards: {
type: "silver",
},
year: 2018,
},
],
},
},
],
},
};
const types = obj.team.table.flatMap((o) => o.list.players.map((o) => o.awards.type));
console.log(types);
2) Using forEach and destructuring as:
const obj = {
team: {
table: [
{
cityCode: 123,
list: {
players: [
{
name: "peter",
school: "x",
awards: {
type: "gold",
},
year: 2019,
},
],
},
},
{
cityCode: 456,
list: {
players: [
{
name: "Dave",
school: "y",
awards: {
type: "silver",
},
year: 2018,
},
],
},
},
],
},
};
const table = obj.team.table;
const types = [];
for (let i = 0; i < table.length; i++) {
const { list: { players } } = table[i]
players.forEach(({ awards: { type }}) => types.push(type))
}
console.log(types);
It will be cleaner to use forEach.
You will need 2 forEach due to your data structure.
But below code will:
check if awards is null
check if awards.type is null
const data = {
"team": {
"table": [
{
"cityCode": 123,
"list": {
"players": [
{
"name": "peter",
"school": "x",
"awards": {
"type": "gold"
},
"year": 2019
}
]
}
},
{
"cityCode": 456,
"list": {
"players": [
{
"name": "Dave",
"school": "y",
"awards": {
"type": "silver"
},
"year": 2018
},
{
"name": "Dave",
"school": "y",
"awards": {
"type": "gold"
},
"year": 2016
}
]
}
},
{
"cityCode": 444,
"list": {
"players": [
{
"name": "James",
"school": "y",
"awards": {
"type": null
},
"year": 2016
}
]
}
},
{
"cityCode": 555,
"list": {
"players": [
{
"name": "Name 101",
"school": "y",
"awards": {
"type": "platinum"
},
"year": 2016
},
{
"name": "Name 102",
"school": "y",
"awards": {
"type": null
},
"year": 2016
},
{
"name": "Name 103",
"school": "y",
"awards": null,
"year": 2016
},
]
}
}
]
}
}
// Expanded your data with more items
const data1 = data.team.table;
let types = []
data1.forEach((item, index) => {
item.list.players.forEach((player) => {
const awards = player.awards;
if (awards !== null && awards.type !== null) {
types = [...types, awards.type];
}
})
})
// Get the list of types
console.log(types);
// Get unique list of types
let unique_types = [...new Set(types)]
console.log(unique_types);
I have the following array of objects
{
"nome": "jose",
"categoria": [
{ "id": "1" },
{ "id": "3" },
]
},
{
"nome": "maria",
"categoria": [
{ "id": "2" },
]
},
{
"nome": "pedro",
"categoria": [
{ "id": "1" },
]
}
I have to reorder in another array of categories. Something like this:
{
"id": "1",
"pessoas": [
{
"nome": "jose",
"categoria": [
{ "id": "1" },
{ "id": "3" },
]
},
{
"nome": "pedro",
"categoria": [
{ "id": "1" },
]
},
]
},
{
"id": "2",
"pessoas": [
{
"nome": "maria",
"categoria": [
{ "id": "2" }
]
},
]
},
I have try with the function reduce(), but I couldn't because it is not an object, but a array of objects (categoria)
const group = data.reduce((r, array) => {
r[array.categoria.id] = [...r[array.categoria.id] || [], array];
return r;
}, {});
Someone can help me please?
You could take an object for grouping by id. Inside of reduce, categoria is iterated as well for getting the needed id.
var data = [{ nome: "jose", categoria: [{ id: "1" }, { id: "3" }] }, { nome: "maria", categoria: [{ id: "2" }] }, { nome: "pedro", categoria: [{ id: "1" }] }],
result = Object.values(data.reduce((r, o) => {
o.categoria.forEach(({ id }) => {
if (!r[id]) r[id] = { id, pessoas: [] };
r[id].pessoas.push(o);
});
return r;
}, {}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
How do I access the following keys within this array of objects using the 'map' method? I want to access:
'id' inside 'moreInfo'
'fore' inside 'distances'
I get undefined for the following fields when I use
a.map((d) => console.log(d.moreInfo.id));
. I want to use the 'map' method itself so that I can render this content in my React application.
let a = [
{
"Id": "huih23432",
"name": "Kevin",
"dob": "26/06/1995",
"nid": "34535353543",
"images": {
"id": "https://picsum.photos/200",
"nid": "https://picsum.photos/200"
}
},
{
"moreInfo": [
{
"id": "243423423423",
"dob": "16/07/1990",
"name": "JD",
"images": {
"id": "https://picsum.photos/200",
"nid": "https://picsum.photos/200"
},
"distances": {
"fore": "0.91",
"towards": "0.5"
}
}
]
}
];
Try this.
let a = [
{
"Id": "huih23432",
"name": "Kevin",
"dob": "26/06/1995",
"nid": "34535353543",
"images": {
"id": "https://picsum.photos/200",
"nid": "https://picsum.photos/200"
}
},
{
"moreInfo": [
{
"id": "243423423423",
"dob": "16/07/1990",
"name": "JD",
"images": {
"id": "https://picsum.photos/200",
"nid": "https://picsum.photos/200"
},
"distances": {
"fore": "0.91",
"towards": "0.5"
}
}
]
}
];
a.filter(d => d.moreInfo)
.map((d)=>{
const moreInfoObj = d.moreInfo.find(y => y.id);
console.log("'id' inside 'moreInfo': " + moreInfoObj.id);
console.log("'fore' inside 'distances': " + moreInfoObj.distances.fore);
});
Actually you data array of objects and each object has different props. You can use destructuring with default values.
let a = [
{
Id: "huih23432",
name: "Kevin",
dob: "26/06/1995",
nid: "34535353543",
images: {
id: "https://picsum.photos/200",
nid: "https://picsum.photos/200",
},
},
{
moreInfo: [
{
id: "243423423423",
dob: "16/07/1990",
name: "JD",
images: {
id: "https://picsum.photos/200",
nid: "https://picsum.photos/200",
},
distances: {
fore: "0.91",
towards: "0.5",
},
},
],
},
];
a.map(({ moreInfo: [{ id, distances: { fore } = {} }] = [{}] }) =>
console.log({ id, fore })
);