Sort array object based on another array in javascript - javascript

How can i sort and rearrange an array that looks like this
fields = [
{
uid: '2c2162cc-37d0-f1e3-96c2-6d9ccb50f38d',
field: new ObjectId("627f816d8443318c6aaa1220"
},
{
uid: '2aa60f96-135b-e179-2b46-516c87a877cc',
field: new ObjectId("6283cb3ca573a56e11587c46"),
}
]
to match the arrangement of this array:
order = [ '6283cb3ca573a56e11587c46', '627f816d8443318c6aaa1220' ]
Here is the output I’m looking for:
[
{
uid: '2aa60f96-135b-e179-2b46-516c87a877cc',
field: new ObjectId("6283cb3ca573a56e11587c46"),
},
{
uid: '2c2162cc-37d0-f1e3-96c2-6d9ccb50f38d',
field: new ObjectId("627f816d8443318c6aaa1220"),
}
]
findIndex and sort but I am very confused
fields.sort((a: any, b: any) => order.indexOf(a.field) - order.indexOf(b.field)) // It does not work

You need to use sort method on the array. And then compare the index of field on the order array.
const data = [
{
uid: '2aa60f96-135b-e179-2b46-516c87a877cc',
field: "6283cb3ca573a56e11587c46",
value: 'test val 6'
},
{
uid: '2c2162cc-37d0-f1e3-96c2-6d9ccb50f38d',
field: "627f816d8443318c6aaa1220",
value: ''
}
]
const order = [ '6283cb3ca573a56e11587c46', '627f816d8443318c6aaa1220' ];
data.sort((a,b) => order.indexOf(a.field) - order.indexOf(b.field));
console.log(data);
Notice: ObjectId class is not defined here, so I changed it to string here for simplicity.

Related

How can I extract and pair the values of an array based object

I'm trying to create a String based upon an object consisting of several key-value pairs.
Example:
[{ name: 'cookie1', value: 'false' },
{ name: 'cookie2', value: '123' },
{ name: 'cookie3',value: 'abc'}]
What I'm trying to achieve (string):
cookie1: false, cookie2: 123, cookie3: abc
I've tried to extract just the val using map like this (played around moving around values):
var output = cookies.map(d => {
return {
"name": d.name,
"value": d.value,
}
})
One way to do this is to map the array of objects into name: value strings and then join them with , :
const data = [{ name: 'cookie1', value: 'false' },
{ name: 'cookie2', value: '123' },
{ name: 'cookie3',value: 'abc'}]
const result = data.map(({ name, value }) => `${name}: ${value}`).join(', ')
console.log(result)

Searching through array of objects that contain arrays of objects efficiently

I am currently searching through an array of objects that contains an array of objects, the data structure looks like the following:
const category = 'general'
const field = 'rating'
const schema = {
categories: [
{
name: 'general',
label: 'General',
fields: [
{
name: 'id',
label: 'Market Street ID',
type: 'string'
},
{
name: 'rating',
label: 'Rating',
type: 'number'
}
]
},
{
name: 'location',
label: 'Location',
fields: [
{
name: 'search',
label: 'Query Parameters',
type: 'string'
}
]
}
]
}
The expected result is to search through the categories array for a given category name (in this case 'general') and then search through the fields for a given field name (in this case 'rating') and return the type associated with the field. I have achieved this by doing the following:
const type = schema.categories
.filter((cat) => cat.name === category)
.map((cat) => {
const fieldData = cat.fields.find((f) => f.name === field)
return fieldData.type
})
console.log(type[0])
I am wondering if there is a more efficient way to search through the array of objects within an array of objects, possibly with the type not being returned in an array
If you only need the first match, you can use Array#find along with optional chaining.
const category="general",field="rating",schema={categories:[{name:"general",label:"General",fields:[{name:"id",label:"Market Street ID",type:"string"},{name:"rating",label:"Rating",type:"number"}]},{name:"location",label:"Location",fields:[{name:"search",label:"Query Parameters",type:"string"}]}]};
const type = schema.categories.find(cat => cat.name === category)
?.fields.find(f => f.name === field).type;
console.log(type);

Comparing two arrays with field in common then pushing to a new array with corresponding grouped fields

general programming problem here.
I have this array called SPACES
[
{
_id: 5e1c4689429a8a0decf16f69,
challengers: [
5dfa24dce9cbc0180fb60226,
5dfa26f46719311869ac1756,
5dfa270c6719311869ac1757
]
},
{
_id: 5e1c4eb9c9461510407d5e81,
challengers: [ 5dfa24dce9cbc0180fb60226, 5dfa26f46719311869ac1756 ],
}
]
And this array called USERS
[
{
_id: 5dfa24dce9cbc0180fb60226,
name: 'Account 1',
email: 'account1#gmail.com',
spaces: [ 5e1c4689429a8a0decf16f69, 5e1c4eb9c9461510407d5e81 ],
},
{
_id: 5dfa26f46719311869ac1756,
name: 'Account 2',
email: 'account2#gmail.com',
spaces: [ 5e1c4689429a8a0decf16f69, 5e1c4eb9c9461510407d5e81 ]
},
{
_id: 5dfa270c6719311869ac1757,
name: 'Account 3',
email: 'account3#gmail.com',
spaces: [ 5e1c4689429a8a0decf16f69 ]
}
]
What I want to do, is go through both, and instead of having the SPACES.challengers array be just IDS, I would like the array to contain each USER object.
So for example, if the USER has an ID that is inside the SPACES.challengers array, then push the user into that array (which will then be the entire object).
SO FAR I have tried this (I am not very good yet):
users.map( ( user ) => {
spaces.map( ( space ) => {
if ( user.spaces.includes( space._id ) ) {
space.challengers.push(user)
}
} );
} );
However, I am not getting inside the IF block. (Even if I did, not sure if it would work OR if this is even how to do it). It feels Odd doing double maps, as I get so many iterations, and it duplicates my push (cause I have no logic to see if it just has been pushed).
Assuming every entry in the Users array has a unique ID, we can build a Hashmap to store (id, index) pairs in order to search efficiently for an ID from Users array while looping through Spaces array.
let spaces = [{_id: '5e1c4689429a8a0decf16f69',challengers: ['5dfa24dce9cbc0180fb60226', '5dfa26f46719311869ac1756', '5dfa270c6719311869ac1757']},{_id: '5e1c4eb9c9461510407d5e81',challengers: [ '5dfa24dce9cbc0180fb60226', '5dfa26f46719311869ac1756' ],}]
let users = [{_id: '5dfa24dce9cbc0180fb60226',name: 'Account 1',email: 'account1#gmail.com',spaces: [ '5e1c4689429a8a0decf16f69', '5e1c4eb9c9461510407d5e81' ],},{_id: '5dfa26f46719311869ac1756',name: 'Account 2',email: 'account2#gmail.com',spaces: [ '5e1c4689429a8a0decf16f69', '5e1c4eb9c9461510407d5e81' ]},{_id: '5dfa270c6719311869ac1757',name: 'Account 3',email: 'account3#gmail.com',spaces: [ '5e1c4689429a8a0decf16f69' ]}]
let IDIndexMapping = {} // To store (_id, index) pairs, in order to improve search efficiency
for(let index in users) // Iterate through Users array using index
IDIndexMapping[users[index]._id] = index; // store (_id, index) pair in IDIndexMapping
// I'm avoiding using `map` and using vanilla `for` loop for space efficiency
// as map returns a new array but with `for` loop, we can perform changes in-place
for(let outerIndex in spaces){ // Iterate through `spaces` array using index
let challengers = spaces[outerIndex].challengers; // Get challengers array
for(let innerIndex in challengers){ // Iterate through challengers array using index
let ID = challengers[innerIndex]; // Get ID
if(ID in IDIndexMapping) // If ID exists in IDIndexMapping
spaces[outerIndex].challengers[innerIndex] = users[IDIndexMapping[ID]]; // Change ID to actual User object
}
}
console.log(spaces)
Output
[ { _id: '5e1c4689429a8a0decf16f69',
challengers: [ [Object], [Object], [Object] ] },
{ _id: '5e1c4eb9c9461510407d5e81',
challengers: [ [Object], [Object] ] } ]
.map and .find should work here. keep it simple.
var spaces = [
{
_id: "5e1c4689429a8a0decf16f69",
challengers: [
"5dfa24dce9cbc0180fb60226",
"5dfa26f46719311869ac1756",
"5dfa270c6719311869ac1757"
]
},
{
_id: "5e1c4eb9c9461510407d5e81",
challengers: ["5dfa24dce9cbc0180fb60226", "5dfa26f46719311869ac1756", "some non existent"]
}
],
users = [
{
_id: "5dfa24dce9cbc0180fb60226",
name: "Account 1",
email: "account1#gmail.com",
spaces: ["5e1c4689429a8a0decf16f69", "5e1c4eb9c9461510407d5e81"]
},
{
_id: "5dfa26f46719311869ac1756",
name: "Account 2",
email: "account2#gmail.com",
spaces: ["5e1c4689429a8a0decf16f69", "5e1c4eb9c9461510407d5e81"]
},
{
_id: "5dfa270c6719311869ac1757",
name: "Account 3",
email: "account3#gmail.com",
spaces: ["5e1c4689429a8a0decf16f69"]
}
],
result = spaces.map(({ _id, challengers }) => ({
_id,
challengers: challengers.map(challenger =>
users.find(user => user._id === challenger)
).filter(row => row)
}));
console.log(JSON.stringify(result, null, 2));
You can create a map of challengers for look-up and then put them in spaces.
//create user map for look-up
userMap = users.reduce((res, val) => ({
...res,
[val._id]: val
}), {});
//change challenger id with user object
inflatedSpaces = spaces.map(s => ({ ...s, challengers: s.challengers.map(c => userMap[c]) }));
You could map the users with a Map.
Beside the destructuring of the object for mapping this answer uses for this part
challengers: challengers.map(
Map.prototype.get, // cb with a prototype and using `this`
new Map(users.map(o => [o._id, o])) // thisArg
)
the above mentioned Map in two parts.
The lower part generates an instance of Map where _id of the users items is used as key and the whole object as value. This instance is uses as thisArg of Array#map, the second parameter.
The upper part is a prototype of Map, used as callback. And while an this object is supplied, a binding (Function#bind) is not necessary.
var spaces = [{ _id: '5e1c4689429a8a0decf16f69', challengers: ['5dfa24dce9cbc0180fb60226', '5dfa26f46719311869ac1756', '5dfa270c6719311869ac1757'] }, { _id: '5e1c4eb9c9461510407d5e81', challengers: ['5dfa24dce9cbc0180fb60226', '5dfa26f46719311869ac1756'] }],
users = [{ _id: '5dfa24dce9cbc0180fb60226', name: 'Account 1', email: 'account1#gmail.com', spaces: ['5e1c4689429a8a0decf16f69', '5e1c4eb9c9461510407d5e81'] }, { _id: '5dfa26f46719311869ac1756', name: 'Account 2', email: 'account2#gmail.com', spaces: ['5e1c4689429a8a0decf16f69', '5e1c4eb9c9461510407d5e81'] },{ _id: '5dfa270c6719311869ac1757', name: 'Account 3', email: 'account3#gmail.com', spaces: ['5e1c4689429a8a0decf16f69'] }],
result = spaces.map(({ _id, challengers }) => ({
_id,
challengers: challengers.map(
Map.prototype.get,
new Map(users.map(o => [o._id, o]))
)
}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Fetch multiple properties from an array of objects and form a new one : Javascript

Been trying to do the following thing:
I have an array of objects ,
var arr = [
{ key: "aabFaa", text: "aabFaa" ,field: "firstName",checked: true},
{ key: "aAaaaa", text: "aAaaaa", field: "firstName", checked: true },
];
Would want to fetch the "text" and "field" out of it and form a new array of objects something like this:
result = [ { "field" : "firstName" , value : "aabFaa" , type :"add"},
{ "field" : "firstName" , value : "aAaaaa" , type: "add"}
]
Here type is hard coded one, where as rest are fetched from the "arr"
Whats the easier way to do this?
Have tried this:
var arr = [
{ key: "aabFaa", text: "aabFaa" ,field: "firstName",checked: true},
{ key: "aAaaaa", text: "aAaaaa", field: "firstName", checked: true },
];
let result = arr.map(a => a.text);
console.log(result)
But this has to be written in multiple lines to get desired properties.Is there an easier approach?
use map with Object Destructuring.
var arr = [
{ key: "aabFaa", text: "aabFaa" ,field: "firstName",checked: true},
{ key: "aAaaaa", text: "aAaaaa", field: "firstName", checked: true },
];
const output = arr.map(({field, text}) => ({field, value: text, type: "add"}));
console.log(output);
Using map seems like a good approach, but you would return a new object and not just one property:
let result = arr.map(a => ({value: a.text, type: 'add', field: a.field}));
let result = arr.map(obj => ({
field: obj.field,
value: obj.text,
type: "add"
}));

javascript (reactJS) best way to access values in a child Array

I've got the following array:
This is an array of Users, and each User has an Attributes array.
Now I want to make a new array with users and only their attributes. Like this
users{
0: {
"phone_number",
"email"
}
}
What would be the best way to achieve this?
thanks
If you need Array of users which contains arrays with users attributes, then you can use Array.prototype.map method:
let users = [
{ Attributes: [ { Name: 'phone_number' }, { Name: 'email' } ] },
{ Attributes: [ { Name: 'phone_number1' }, { Name: 'email1' } ] }
];
let result = users.map((user) => user.Attributes.map((attr) => attr.Name));
console.log(result)

Categories

Resources