Sort Array in Array - arrays

I have following array result:
Example:
[
{
id: "1",
league: {
name: "World Club Friendlies",
team: "Simple 1 & Simple 2"
}
},
{
id: "2",
league: {
name: "Senegal Ligue 2",
team: "Simple"
}
},
{
id: "3",
league: {
name: "World Club Friendlies",
team: "Simple 3 & Simple 4"
}
},
]
The First and Third league names are similar.
The above code output looks like this:
League Name: World Club Friendlies / Team: Simple 1 & Simple 2
League Name: Senegal Ligue 2 / Team: Simple
League Name: World Club Friendlies / Team: Simple 3 & Simple 4
Now i need to print following result:
League Name: World Club Friendlies / Team: Simple 1 & Simple 2 & Simple 3 & Simple 4
League Name: Senegal Ligue 2 / Team: Simple
I have somthing like this code:
foreach($content as $result){
echo $result['league']['name'];
echo $result['team'];
}

Use reduce and check for team name as key and apply the condition that you want as follows:
var data = [{
id: "1",
league: {
name: "World Club Friendlies",
team: "Simple 1 & Simple 2"
}
},
{
id: "2",
league: {
name: "Senegal Ligue 2",
team: "Simple"
}
},
{
id: "3",
league: {
name: "World Club Friendlies",
team: "Simple 3 & Simple 4"
}
},
]
var res = data.reduce((acc, curr) => {
if (acc[curr.league.name]) {
acc[curr.league.name] = {
name: curr.league.name,
team: acc[curr.league.name].team + " & " + curr.league.team
}
} else {
acc[curr.league.name] = {
name: curr.league.name,
team: curr.league.team
}
}
return acc;
}, {});
for (data in res) {
console.log("League name: " + res[data].name + "/Team:" + res[data].team)
}

Related

save mongodb coordinates array into the variable

I use a mongodb 5.0 version and I have a collection named georestaurants with a 2dsphere index
[
{ v: 2, key: { _id: 1 }, name: '_id_' },
{
v: 2,
key: { 'address.location': '2dsphere' },
name: 'add.idx',
'2dsphereIndexVersion': 3
}
]
This is one example document from my collection
db.georestaurants.findOne()
{
_id: ObjectId("61eeedc059814f22a1f6a481"),
address: {
building: '1007',
street: 'Morris Park Ave',
zipcode: '10462',
location: { type: 'Point', coordinates: [ -73.856077, 40.848447 ] }
},
borough: 'Bronx',
cuisine: 'Bakery',
grades: [
{ date: ISODate("2014-03-03T00:00:00.000Z"), grade: 'A', score: 2 },
{ date: ISODate("2013-09-11T00:00:00.000Z"), grade: 'A', score: 6 },
{
date: ISODate("2013-01-24T00:00:00.000Z"),
grade: 'A',
score: 10
},
{ date: ISODate("2011-11-23T00:00:00.000Z"), grade: 'A', score: 9 },
{
date: ISODate("2011-03-10T00:00:00.000Z"),
grade: 'B',
score: 14
}
],
name: 'Morris Park Bake Shop',
restaurant_id: '30075445'
}
I would like to get the distance between two restaurants from a query, but first of all I need to save (only) the coordinates into a variable.
My query is:
var coord=db.georestaurants.findOne({"name":/^Morris\ Park\ Bake/},{"_id":0, "address.location.coordinates":1})
coord
{
address: { location: { coordinates: [ -73.856077, 40.848447 ] } }
}
Can I save into a coord var, only longitude, latitude data[ -73.856077, 40.848447 ] or extract this info by making a query to the coord variable?
Thanks in advance!
In next statement
var coord = db.geo_restaurants.find({ "name": /^Morris\ Park\ Bake/} , {coord:"$address.situacio.coordinates", "_id":0 } )
simplifies a bit, but there are still plenty of items
coord
[ { coord: [ -73.856077, 40.848447 ] } ]
I only want into 'coord' variable
this
[ -73.856077, 40.848447 ]
thanks

How to combine elements in an array?

I'm trying to combine the "role" parameter for "Project" objects with the same "id" and "title" parameters in the myProjects array below:
struct Project: Identifiable {
var id: String
var title: String
var role: String
}
var myProjects = [Project(id: "1", title: "Sunset", role: "2nd AD"),
Project(id: "2", title: "Lights", role: "Mix Tech"),
Project(id: "2", title: "Lights", role: "Sound Mixer"),
Project(id: "3", title: "Beach", role: "Producer")]
var updatedProjects: [Project] = []
// The goal is to update myProjects to show the following:
updatedProjects = [Project(id: "1", title: "Sunset", role: "2nd AD"),
Project(id: "2", title: "Lights", role: "Mix Tech & Sound Mixer"),
Project(id: "3", title: "Beach", role: "Producer"]
This is what I have attempted so far, the result is giving me duplicate combinations of the roles parameter for each project in the myProjects array.
var dupProjects = myProjects
for myProject in myProjects {
for dupProject in dupProjects {
if myProject.id == dupProject.id {
let combinedRoles = "\(myProject.role) & \(dupProject.role)"
updatedProjects.append(Project(id: myProject.id,
title: myProject.title,
role: combinedRoles))
}
}
}
print(updatedProjects)
// [__lldb_expr_48.Project(id: "1", title: "Sunset", role: "2nd AD & 2nd AD"),
__lldb_expr_48.Project(id: "2", title: "Lights", role: "Mix Tech & Mix Tech"),
__lldb_expr_48.Project(id: "2", title: "Lights", role: "Mix Tech & Sound Mixer"),
__lldb_expr_48.Project(id: "2", title: "Lights", role: "Sound Mixer & Mix Tech"),
__lldb_expr_48.Project(id: "2", title: "Lights", role: "Sound Mixer & Sound Mixer"),
__lldb_expr_48.Project(id: "3", title: "Beach", role: "Producer & Producer")]
You can use a dictionary to group them by id, combine the roles, then convert the group back to a single Project
let combined = Dictionary(grouping: myProjects) { element in
return element.id
}.compactMapValues { projects -> Project? in
var first = projects.first
first?.role = projects.map { $0.role }.joined(separator: " & ")
return first
}.values.map { $0 }

NextJs / React: Organizing Array

I'm having issues understanding how to best manipulate an array to get the data I want. From the research I've done, there's multiple ways, but I'm unclear on which is most optimized.
I want to display a simple list, with the items broken down by country, then state, then organized alphabetically by city. The array is formatted as follows:
[
{
id: 1,
name: "Place 1",
state: "Florida",
city: "Boca Raton",
country: "US",
},
{
id: 2,
name: "Place 2",
state: "Florida",
city: "Daytona Beach",
country: "US",
},
{
id: 3,
name: "Place 3",
state: "Kansas",
city: "Lenexa",
country: "US",
},
{
id: 4,
name: "Place 4",
state: "Harju",
city: "Tallinn",
country: "EE",
},
]
An example of the desired outcome is:
US
Florida
Place 1
Place 2
Kansas
Place 3
EE
Harju
Place 4
I see a lot of people saying to utilize ES6 for this, but I'm not sure the best way to approach it. Manipulate the original array response? Is there some way I can loop through them?
Here's an approach that only requires a single loop.
const data = [];
let result = {};
data.forEach(({ name, state, country }) => {
if (!result[country]) {
result[country] = {};
}
if (!result[country][state]) {
result[country][state] = [name];
}
else {
result[country] = {
...result[country],
[state]: [
...result[country][state],
name
]
};
}
});
console.log(result);
Output
{
US: { Florida: [ 'Place 1', 'Place 2' ], Kansas: [ 'Place 3' ] },
EE: { Harju: [ 'Place 4' ] }
}
I'm sure the if-else part can be removed by using spread operator and operator chaining, but I wasn't able to figure that out.
If your environment supports operator chaining, here's a smaller solution
const data = [];
let result = {};
data.forEach(({ name, state, country }) => {
result[country] = {
...result[country],
[state]: [
...(result?.[country]?.[state] || []),
name
]
};
});
console.log(result);

How to merge two array of objects based on a key in Dart/Flutter

I have 2 arrays of maps where one of them has product ids and quantities; and the other one has product ids, product names and price:
List<Map<String, dynamic>> arr1 = [
{ id: "1", name:"First Item", price: 10 },
{ id: "2", name: "Second Item", price: 12 }
];
List<Map<String, dynamic>> arr2 = [
{ id: "1", quantity: 1 },
{ id: "2", quantity: 3 },
{ id: "3", quantity: 2 }
];
Now I need to get total price of products by combining two arrays by obtaining sum of price * quantites.
I need an array similar to this:
List<Map<String, dynamic>> arr3 =[
{ id: "1", name:"First Item", price: 10, quantity: 1 },
{ id: "2", name: "Second Item", price: 12, quantity: 3 }
];
How can I merge them into one array based on their ids?
You can merge the array by mapping the first array to the second one.
final arr3 = arr1.map((product) {
final quantity = arr2
.where((quantities) => quantities["id"] == product["id"])
.map((quantities) => quantities["quantity"] as int)
.first;
return product..["quantity"] = quantity;
});
Full example: https://dartpad.dev/67148d132cb930bc6f1cee6a8a4fcff1

Sort and group objects alphabetically by the first letter from an array in Angular?

How can I sort and group objects alphabetically by the first letter from an array in angular? I have seen the example to do this Sort and group objects alphabetically in Javascript and the exact answer and output json i am looking in Angular.
As of now My api json is like this stackblitz
Expexted api json would like this stackblitz
I have tried this but i am unable to found the solution in angular.
real Json:
employees = [
{ name: "Abigail", age: "25" },
{ name: "Axle", age: "29" },
{ name: "Brianna", age: "25" },
{ name: "Brooklyn", age: "23" },
{ name: "Camila", age: "24" },
{ name: "Charlotte", age: "28" },
{ name: "David", age: "22" }
];
expecting json after sort and group objects alphabetically by the first letter from an array would like:
[
{
"alphabet": "A",
"record": [
{ "name": "Abigail", "age": "25" },
{ "name": "Axle", "age": "29" }
]
},
{
"alphabet": "B",
"record": [
{ "name": "Brianna", "age": "25" },
{ "name": "Brooklyn", "age": "23" }
]
},
{
"alphabet": "C",
"record": [
{ "name": "Camila", "age": "24" },
{ "name": "Charlotte", "age": "28" }
]
},
{
"alphabet": "D", "record": [
{ "name": "David", "age": "22" }
]
}
]
expected output like:
A
Abigail
Axle
B
Brianna
Brooklyn
C
Camila
Charlotte
D
David
As mentioned in the comment, there is no Typescript specific way to sort and group the data. You could the JS Array#reduce to group the objects to your requirement.
Try the following
const employees = [ { name: "Abigail", age: "25" }, { name: "Axle", age: "29" }, { name: "Brianna", age: "25" }, { name: "Brooklyn", age: "23" }, { name: "Camila", age: "24" }, { name: "Charlotte", age: "28" }, { name: "David", age: "22" } ];
const output = employees
.reduce((acc, curr) => {
const idx = acc.findIndex(e => e.alphabet === curr.name[0]);
if (idx === -1) {
acc.push({ alphabet: curr.name[0], record: [curr] });
}
else {
acc[idx].record.push(curr);
acc[idx].record.sort((r1, r2) => r1.name > r2.name ? 1 : -1);
}
return acc;
}, [])
.sort((e1, e2) => e1.alphabet > e2.alphabet ? 1 : -1);
console.log(output);
It would look like following in the Stackblitz.
export class ExpansionOverviewExample {
#ViewChild(MatAccordion, { static: false }) accordion: MatAccordion;
employees = [
{ name: "Brianna", age: "25" },
{ name: "Axle", age: "29" },
{ name: "David", age: "22" },
{ name: "Brooklyn", age: "23" },
{ name: "Camila", age: "24" },
{ name: "Abigail", age: "25" },
{ name: "Charlotte", age: "28" }
];
constructor() {
this.employees = this.employees
.reduce((acc, curr) => {
const idx = acc.findIndex(e => e.alphabet === curr.name[0]);
if (idx === -1) {
acc.push({ alphabet: curr.name[0], record: [curr] });
} else {
acc[idx].record.push(curr);
acc[idx].record.sort((r1, r2) => (r1.name > r2.name ? 1 : -1));
}
return acc;
}, [])
.sort((e1, e2) => (e1.alphabet > e2.alphabet ? 1 : -1));
}
}
You could also use safe navigation operator ?. in the template so you don't get any undefined errors before the reduce is complete.
<div *ngFor="let mani of employees">
<div>
<p>{{mani?.alphabet}}</p>
<p *ngFor="let group of mani?.record"> {{ group?.name }}</p>
<hr>
</div>
</div>
I've updated your Stackblitz

Resources