This question already has answers here:
How do I group items in an array by date?
(4 answers)
Closed 11 months ago.
I have an array of objects for the next three days, so every day it changes. I want to sort out the objects by the dates.
Each object has these elements.
dt: 1649278800
dt_txt: "2022-04-06 21:00:00"
I would like to sort the objects depending on the date, and create a new array with the objects which have the same date. So all the "2022-04-06" dates in one array all the "2022-04-07" in an another array etc.
You can pass a comparer to the sort function that will compare the specific dt_txt property of the objects in the array you wish to sort. After then the sorted array will be grouped by the property dt_txt, shortened including only the date, and each group will be held in the map variable by that value as a key and an array of objects belonging to that datetime:
const compare = ((a, b) => new Date(a.dt_txt).getTime() -
new Date(b.dt_txt).getTime());
let objectsList = [
{ dt: 1649278800, dt_txt: "2019-04-06 21:00:00" },
{ dt: 6589034985, dt_txt: "2022-04-30 21:00:00" },
{ dt: 9038475923, dt_txt: "2004-12-01 21:00:00" },
{ dt: 5940382093, dt_txt: "2011-08-05 21:00:00" },
];
objectsList.sort( compare );
let map = {};
objectsList.forEach((o, i) => {
let shortened = o.dt_txt.substring(0, 10);
if(typeof map[shortened] === 'undefined')
map[shortened] = [];
map[shortened].push(o);
});
console.log({ map });
.as-console-wrapper { min-height: 100%!important; top: 0; }
This answer was inspired by this other one: Sort array of objects by string property value
Related
This question already has answers here:
Sorting an array of objects by property values
(35 answers)
Closed 2 years ago.
I have an array of object and want to reorder objects inside array Is there any way to do that?
var obj = [ {start: 12, end: 14}, {start: 2, end:8}]
I should check if start date of first object is greater than second object's start date and change objects order, The result in this case should be =>
var obj = [ {start: 2, end:8}, {start: 12, end: 14}]
I know about sorting inside object but cant find way to reorder the whole object.
Use your expeceted property to conduct compared function
var obj = [
{ start: 12, end: 14 },
{ start: 2, end: 8 },
]
const res = obj.sort((a, b) => a.start - b.start)
console.log(res)
This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
Closed 4 years ago.
I have an array of json objects:
[ {id:0, name:'A'}, {id:1, name:'B'}...{id:n, name:'N'} ]
How do i get the value (name) base on a given id, without iterating the array? Perhaps using map or some filter method...
const arr = [ {id:0, name:'A'}, {id:1, name:'B'},{id:3, name:'N'} ];
const inputId = 1;
const foundObj = arr.find(({ id }) => id === inputId);
if (foundObj) console.log(foundObj.name);
This still does iterate the array internally, though (as any method will).
This find method will find object based on your object property and value.
ArrayName.find(x => x.id === 0);
let array = [ {id:0, name:'A'}, {id:1, name:'B'}, {id:'n', name:'N'} ]
//To search in array we must iterate. But if you want to optimise performance for multiple searches you can map it to object by id.
let map = array.reduce((acc,element)=>{acc[element.id]=element;return acc;},{})
console.log(map[0])
console.log(map[1])
console.log(map.n) //As n was used as id.
Maps take one iteration to construct. Value retrieval thereon is sublinear.
// Input.
const input = [{id: 0, name:'A'}, {id: 1, name:'B'}, {id: 13, name:'N'}]
// To Map.
const toMap = (A) => new Map(A.map(x => [x.id, x]))
// Output.
const output = toMap(input)
// Proof.
console.log(output.get(0))
console.log(output.get(1))
console.log(output.get(13))
When you want to find an element in a collection, array might not be the best choice, objects or maps are much better in that case.
Each time you have to find an element, you would have to iterate over the array which would take O(n) time.
To avoid this, you could have an API layer in the middle, to convert your array into an a data structure which maps values by unique keys. You could achieve this by a plain Javascript Object.
That way you could find your element by id in O(1) without any iteration.
//original data
let arr = [ {id:0, name:'A'}, {id:1, name:'B'}, {id:2, name:'N'} ];
//convert it into object
let obj = arr.reduce((acc, curr) => {
acc[curr.id] = curr;
return acc;
}, {});
//modified data
{ 0: { id: 0, name: 'A' },
1: { id: 1, name: 'B' },
2: { id: 2, name: 'N' } }
//Now, you can look up value on any id as
obj[id].name;
This question already has answers here:
Sorted a javascript array of objects by an object property
(6 answers)
Closed 5 years ago.
I currently have an array object (not sure if this is the accurate name) that is comprised of nested key value pairs. I want to be able to sort this by the values within the nested objects.
For example:
var ObjArray = [
{ id = 1,
info = {
number = 4,
name = "foo"
}
},
{ id = 4,
info = {
number = 12,
name = "bar"
}
},
{ id = 9,
info = {
number = 2,
name = "fizz"
}
}
];
So ideally I could sort this object based on the 'number' property, and the resulting array object would have sub objects ordered by the number value within the info.
I've found a similar question (Sorting an object of nested objects in javascript (maybe using lodash?)) but doesn't account for another level of nested objects.
The sorting function needed is
ObjArray.sort((a,b) => a.info.number - b.info.number);
This will sort them ascending
For descending :
ObjArray.sort((a,b) => b.info.number - a.info.number);
var ObjArray = [{
id: 1,
info: {
number: 4,
name: "foo"
}
},
{
id: 4,
info: {
number: 12,
name: "bar"
}
},
{
id: 9,
info: {
number: 2,
name: "fizz"
}
}
];
ObjArray.sort((a,b) => a.info.number - b.info.number);
console.log(ObjArray);
This question already has answers here:
Sorting an array of objects by property values
(35 answers)
Closed 6 years ago.
I want to order a javascript list containing object according to a key,
var a = [{order: 1, item: 'shoes'}, {order: 3, item: 'jeans'}, {order: 2, item: 'shirt'}, {order: 1, item: 'coat'}]
Here I want to order according to order from lower to upper like:
var b = a.filter(data => data.order) // have some check here
How can I do that ?
you need to sort by the property so you can use a functional style to curry the key, and return a function that Array.prototype.sort can use.
var clothes = [
{ order: 1, item: 'shoes' },
{ order: 3, item: 'jeans' },
{ order: 2, item: 'shirt' },
{ order: 1, item: 'coat' }
]
const sortBy = key => (a, b) => a[key] - b[key]
console.log(
clothes.sort(sortBy('order'))
)
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>
If you are using lodash, you can do (docs)
_.sortBy(list, el => el.order);
If you are not (and I believe you should), you can take a look at their source code for hints ;)
I have this array of objects
[ { id: '573267d06b2957ab24c54d59' },
{ id: '573267d06b2957ab24c54d5a' },
{ id: '573267d06b2957ab24c54d5b' },
{ id: '573267d06b2957ab24c54d5c' },
{ id: '573267d06b2957ab24c54d5d' }
]
I wish to convert it to the following in NodeJs
[ '573267d06b2957ab24c54d59',
'573267d06b2957ab24c54d5a',
'573267d06b2957ab24c54d5b',
'573267d06b2957ab24c54d5c',
'573267d06b2957ab24c54d5d'
]
It seems like it should be easy given the right library/package, but I am struggling to find the right wording to "flatten" the array into the IDs of the contained objects.
Say your array of objects is called arr, just do this:
var arrayOfStrings = arr.map(function(obj) {
return obj.id;
});
map will iterate over the array and create a new array based on how you define your function. In this case we return the value of the id key in each case to build out the desired array of ids.