Sort objects inside array [duplicate] - javascript

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)

Related

Mapping keys into objects with Javascript [duplicate]

This question already has answers here:
How to transpose a javascript object into a key/value array
(11 answers)
Closed 8 months ago.
This is the object I have:
years = {1924:2, 1934: 10, 2010: 4}
I would like to transform this into:
years = [{year: 1924, items: 2}, {year: 1934, items: 10}, {year: 2010, items: 4}]
This is the code I came up with so far (which obviously doesn't work):
var years2 = {};
for (var i = 0; i < years.length; ++i) {
years2.push({ years: [$key] })
};
I am stuggling to find the right way to access the unnamed keys and map these into their own objects.
(I am still learning JS and I know this is basics, but somehow cannot get my head around it.. )
You can create key value pairs from the object with Object entries and map them to new array
const years = {1924:2, 1934: 10, 2010: 4}
const ans = Object.entries(years).map(([key,value]) => {
return {year: key, items: value}
})
console.log(ans);
You can get entries, then convert to object with map
const years = {1924:2, 1934: 10, 2010: 4}
const result = Object.entries(years).map(([year, items]) => ({year: year, items: items}))
console.log(result)

Sorting a changeing array of objects by date [duplicate]

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

findIndex of item in array of object where object property match [duplicate]

This question already has answers here:
findIndex() javascript array object
(2 answers)
How do I get the index of object in array using angular?
(5 answers)
Get objects position in array
(3 answers)
Closed 1 year ago.
I have an array of object as follow :
[ {label: "<p>Opacity | %<br/></p>", customRow: false, id: 0, items: Array(13)},
{label: "Brand_hs_id", customRow: false, id: 0, items: Array(13)},
{label: "<p>PPI |</p>", customRow: false, id: 0, items: Array(13)},
{label: "Brightness | %", customRow: false, id: 0, items: Array(13)
]
I want to findIndex of object where label value matches. for example if I pass the "Brightness | %" it should return 3.
I checked
const array1 = [5, 12, 8, 130, 44];
const isLargeNumber = (element) => element > 13;
console.log(array1.findIndex(isLargeNumber));
// expected output: 3
but not sure how to do it in array of objects .
Try something like as follows:
let val = [{id:"1002", address:"usa"},
{id:"1004", address:"canada"},
{id:"1006", address:"sweden"}];
let index = val.findIndex(x => x.address === "canada");
console.log(index); //Here index will be returned
do it like this
const array1 = [{age:5}, {age:12},{age:8} , {age:130}, {age:44}];
const isLargeNumber = (element) => element.age > 13;
console.log(array1.findIndex(isLargeNumber));

javascript list containing object ordering according to a key [duplicate]

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 ;)

Loop and Combine Time Ranges in an Array

I am trying to read through an array of objects (that are start/end times) and combine two (or more) of those times if they are back to back.
ie. the first objects end time is the same as the next objects start time. If they are, combine them. Then check the newly combined objects end time with the next object in the array
Here is a simplified array of times:
var times = [
{
start: 1,
end: 2
},{
start: 2,
end: 3
},{
start: 4,
end: 5
},{
start: 6,
end: 7
},
]
I would like that (or have a diff Array) to output like the below:
var newTimes = [
{
start: 1,
end: 3
},{
start: 4,
end: 5
},{
start: 6,
end: 7
},
]
It gets trickier if there are 3 times in a row.
var threeTime = [
{
start: 1,
end: 2
},{
start: 2,
end: 3
},{
start: 3,
end: 5
},{
start: 6,
end: 7
},
]
The above should turn into:
var newThreeTimes = [
{
start: 1,
end: 5
},{
start: 6,
end: 7
},
]
The original array of times will always be sorted from oldest (smallest start time) to newest (largest start time). The output does not need to be in any specific order. All time objects will be moment times.
Can someone help me solve this?
This is the code i have come up with
function mergeArr(arr) {
// Sort the array in descending order
arr.sort(function(a, b) {
return b.start - a.start;
});
// Traverse from the top as you will need to remove the elements
// Merge the elements based on start of one and end of the previous
for (var i = arr.length - 1; i > 0; i--) {
if (arr[i].end == arr[i - 1].start) {
arr[i].end = arr[i - 1].end;
arr.splice(i - 1, 1);
}
}
// Sort it again in reverse order.
return arr.sort(function(a, b) {
return a.start - b.start;
});
}
Comments are making the code self explanatory.
Working Fiddle

Categories