I have an Array I am trying to sort alphabetically by the description, unfortunately it's not doing anything.
I believe my code is right as it worked before, maybe I'm missing something basic but I can't see it.
Here's the array
{
status:200
content:{
records:[
0:{
id:"recCmTdywUZc3mRYr"
createdTime:"2023-01-28T22:24:08.000Z"
fields:{
Description:"Apple"
Qty:9
}
}
1:{
id:"recDg7dLnRsdwfvbc"
createdTime:"2023-01-28T22:24:08.000Z"
fields:{
Description:"Orange"
Qty:6
}
}
2:{
id:"recDhHyMIAS1qGu3E"
createdTime:"2023-01-28T22:30:56.000Z"
fields:{
Description:"Pear"
Qty:1
}
}
3:{
id:"recIMEr6bOtpS1Kdd"
createdTime:"2023-01-28T22:30:55.000Z"
fields:{
Description:"Banana"
Qty:10
}
}
]
}
}
Here's the code I'm using to sort the array:
sorted = inputArray.items.slice();
sorted.sort((a, b) => a. Description.localeCompare(b. Description))
Assuming records is an array, you need to get the right value with
const
data = { status: 200, content: { records: [{ id: "recCmTdywUZc3mRYr", createdTime: "2023-01-28T22:24:08.000Z", fields: { Description: "Apple", Qty: 9 } }, { id: "recDg7dLnRsdwfvbc", createdTime: "2023-01-28T22:24:08.000Z", fields: { Description: "Orange", Qty: 6 } }, { id: "recDhHyMIAS1qGu3E", createdTime: "2023-01-28T22:30:56.000Z", fields: { Description: "Pear", Qty: 1 } }, { id: "recIMEr6bOtpS1Kdd", createdTime: "2023-01-28T22:30:55.000Z", fields: { Description: "Banana", Qty: 10 } }] } },
records = data.content.records.slice();
records.sort((a, b) => a.fields.Description.localeCompare(b.fields.Description));
console.log(records)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Why sorted = inputArray.items.slice() ? With the structure you posted it should be sorted = inputArray.content.records.slice()
And then
sorted.sort((a, b) => a.fields.Description.localeCompare(b.fields.Description))
Related
I have 2 arrays, one (array1) which needs to be sorted based on its inner key, role, according to another (array2). I have tried different solutions but cannot progress any further since i don't understand what steps i should take
I have the following output: Array1
{
"id":12,
"roles":[
{
"id":12,
"role":"team_player",
"sub_role":null,
"team_meta":{
"default_player_role":{
"pos":null,
"role":"LWB"
}
}
}
],
"user_email":"w#w.w"
},
{
"id":1575,
"roles":[
{
"id":1672,
"role":"team_player",
"sub_role":null,
"team_meta":{
"default_player_role":{
"pos":null,
"role":"LB"
}
}
}
],
"user_email":"j#j.s"
},
{
"id":1576,
"roles":[
{
"id":1673,
"role":"team_player",
"sub_role":null,
"team_meta":{
"default_player_role":{
"pos":null,
"role":"CAM"
}
}
}
],
"user_email":"E#E.E",
},
And i want to order the array above according to the order of this:
const array2 = ["LWB", "LB", "CAM"]
The issue i'm having is that the given key that the sorting should be according to in array1 is too deep, and I haven't found any way to map the "role" from the first array with the array2.
You need to get role and with this value get the index for the order.
const
getRole = ({ roles: [{ team_meta: { default_player_role: { role } }}] }) => role,
data = [{ id: 1576, roles: [{ id: 1673, role: "team_player", sub_role: null, team_meta: { default_player_role: { pos: null, role: "CAM" } } }], user_email: "E#E.E" }, { id: 12, roles: [{ id: 12, role: "team_player", sub_role: null, team_meta: { default_player_role: { pos: null, role: "LWB" } } }], user_email: "w#w.w" }, { id: 1575, roles: [{ id: 1672, role: "team_player", sub_role: null, team_meta: { default_player_role: { pos: null, role: "LB" } } }], user_email: "j#j.s" }],
order = ["LWB", "LB", "CAM"];
data.sort((a, b) => order.indexOf(getRole(a)) - order.indexOf(getRole(b)));
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Over several loops you can also sort it but probably not an elegant solution:
const nestedArray = [...]; // Replace Array
const sortByArray = ["LWB", "LB", "CAM"];
const sortedArray = [];
sortByArray.forEach(function(sortByArrayValue) {
nestedArray.forEach(function(nestedArrayValue) {
nestedArrayValue.roles.forEach(function(role) {
if (role.team_meta.default_player_role.role === sortByArrayValue) {
sortedArray.push(nestedArrayValue);
}
});
});
});
My goal is to loop over some data and get something like the following output, so if anyone can help me out it would be greatly appreciated. In order to display something like this, I tried looping something and displaying it in a loop.
let selectedOrders: {code?: string;selectedList?: [{ name: string; language: string }];
let set = new Set();
order.orders.map((list) => {
if (!set.has(list.code)) {
selectedOrders.push({
code: list.code,
selectedList: [
{
name: list.name!,
language: list.language!,
},
],
});
set.add(list.serviceCode);
return;
}
selectedOrders.push({
selectedList: [
{
name: list.name!,
language: list.language!,
},
],
});
}
});
return selectedOrders;
});
Input
{
code:"A"
name:"php"
desc:"language"
order:2
},
{
code:"A"
name:"javascript"
desc:"language"
order:1
},
Output
code: A
selectedList: [{
name:"javascript"
desc:"language"
},
{
name:"php"
desc:"language"
}]
}
let data = [
{
code: "A",
name: "php",
desc: "language",
order: 2,
},
{
code: "B",
name: "c++",
desc: "language",
order: 3,
},
{
code: "A",
name: "javascript",
desc: "language",
order: 1
}];
let result = data.reduce((acc: any[], item) => {
const { name, desc, order, code } = item;
if (acc.some((a: any) => code == a.code)) {
let obj: any = acc.find((a: any) => code == a.code)!;
obj.selectedList.push({
name, desc, order
});
} else {
acc.push({
code,
selectedList: [{ name, desc, order }]
});
}
return acc;
}, []);
console.log(result);
Just change any to your required type.
[Noob to Javascript and React] I am using an API that returns an object with values like this. AAPL, AMZN, FB, GOOGL, can be anything based on the function's string array input.
{
AAPL: { price: 329.99 },
AMZN: { price: 2563.05 },
FB: { price: 239.93 },
GOOGL: { price: 1469.12 }
}
How could I consider dynamically mapping a response like this into a state object like this? The id property doesn't exist, it needs to be created.
state = {
stocks: [ { id: 1, name: 'AAPL', price: 329.99 }, { id: 2, name: 'AMZN', price: 2563.05 }, ...]
}
I'm able to successfully print the stock names and their prices separately but I am having trouble figuring out how I could wire them into a state object like what's above.
function getCurrentPriceOfBatchStocks(_stocks) {
iex
.symbols(_stocks)
.price()
.then(res => {
console.log(typeof res);
console.log(res);
console.log(Object.keys(res));
console.log(Object.values(res));
});
}
Not sure where you're getting id from, so I'm using idx as an example.
const stocks = Object.keys(resp).map((key, idx) => ({ id: idx + 1, name: key, price: resp[key] }))
Here is an implementation. With Object.entries, you get an array with an array of [key, value] of your original object. And you can map this array to a different format.
You can check the result with the Run code snippet button.
let st = {
AAPL: { price: 329.99 },
AMZN: { price: 2563.05 },
FB: { price: 239.93 },
GOOGL: { price: 1469.12 }
}
let stocks = Object.entries(st).map(([key, value], index) => ({id: index + 1, name: key, price: value.price}))
console.log(stocks)
const res={
AAPL: { price: 329.99 },
AMZN: { price: 2563.05 },
FB: { price: 239.93 },
GOOGL: { price: 1469.12 }
}
console.log(Object.entries(res).map((entry,index)=>{
return {
id:index+1,
name:entry[0],
...entry[1]
}
}));
I got this data set from collection
{
item: 124001
price: 6
},
{
item: 124001
price: 6
},
{
item: 124121
price: 16
},
{
item: 124121
price: 13
},
{
item:n
price: x
}
from code:
let INDX = [xxx,xxx,xxx,xxx, ..n]
auctions.aggregate([
{
$match: { item: { $in: INDX }}
}
The problem is right after it, in the $group stage. For example I'd like to receive $min, $max or $avg 'price' for every unique/distinct item.
When I'm trying to use:
{
$group: {
min_1: { $min: "$price",}
}
}
I receive just $min from all data,
[ { _id: 0, min_1: 0 } ]
but I need something like:
{ _id: 124119, min_1: 66500 },
{ _id: 124437, min_1: 26398 }
Ok, here is a simple answer:
Just don't forget about _id field and use it, at $group stage, just like:
{
$group: {
_id: "$item",
min_1: {
$min: '$price',
}
}
}
I'm certain this question is very common, but I can't seem to find a robust answer for my use case.
I have an Array of objects with nesting in two levels. Here is an example of the array:
let array = [
{ company: 'CompanyName1',
child: [
{ title: 'title1a',
baby: [
{ title: 'title1ab' },
{ title: 'title1abc' }
]
},
{ title: 'title2a',
baby: [
{ title: 'titleb2abcd' },
{ title: 'titleb2abcde' }
]
}
]
},
{ company: 'CompanyName2',
child: [
{ title: 'title2b',
baby: [
{ title: 'titleb3ab' },
{ title: 'titleb3abc' }
]
}
]
}
]
And this is my expected Array:
let newArray = [
{
company: 'companyName1',
child_title_0: 'title1a',
child_title_1: 'title1a',
child_baby_0: 'title1ab',
child_baby_1: 'title1abc',
child_baby_2: 'title1abcd',
child_baby_3: 'title1abcde',
},
{
company: 'companyName2',
child_title_0: 'title2b',
child_baby_0: 'titleb3ab',
child_baby_1: 'titleb3abc',
}
]
Basically I need to flatten each of the top level objects of the array. Since the nested objects have the same keys (follow a model, and are dynamic -- some items have 10 nested objects, some 0, etc.) I have to dynamically generate each of the new keys, possibly based in the index of the loops.
Any help -- direction is appreciated.
Thanks!
You can use the map function to return a manipulated version of each object in the array.
let results = [
{
company: 'CompanyName1',
child: [
{
title: 'title1a',
baby: [
{ title: 'title1ab' },
{ title: 'title1abc' }
]
},
{
title: 'title2a',
baby: [
{ title: 'titleb2abcd' },
{ title: 'titleb2abcde' }
]
}
]
},
{
company: 'CompanyName2',
child: [
{
title: 'title2b',
baby: [
{ title: 'titleb3ab' },
{ title: 'titleb3abc' }
]
}
]
}
];
let flattened = results.map(company => {
let childCount = 0, babyCount = 0;
company.child.forEach(child => {
company['child_title_'+childCount] = child.title;
child.baby.forEach(baby => {
company['child_baby_'+babyCount] = baby.title;
babyCount++;
});
childCount++;
});
delete company.child;
return company;
});
console.log(flattened);