How to sort by key "name"? (in alphabetical order)
It is not working:
views.sort(function(a, b) {
var x = a.name.toLowerCase(),
y = b.name.toLowerCase();
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
})
Please help me.
How to sort by key "name"? (in alphabetical order)
It is not working:
views.sort(function(a, b) {
var x = a.name.toLowerCase(),
y = b.name.toLowerCase();
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
})
Please help me.
You an use localeCompare
for comparing strings:
var views = {
viewA: { name: 'Build Plus' },
viewB: { name: 'Columns' },
viewC: { name: 'PowerPack Templates', other: 'field' },
viewD: { name: 'Blog Posts' }
};
var viewsArr = Object.keys(views).map(function (key) { return views[key]; });
viewsArr.sort(function(a, b) {
var x = a.name.toLowerCase(),
y = b.name.toLowerCase();
return x.localeCompare(y);
})
console.log(viewsArr);
Update: You are receiving object with keys and values. You need to take values in the array first and then sort them.
See Converting a JS object to an array using jQuery
In your case it will be:
var viewsArr = Object.keys(views).map(function (key) { return views[key]; });
// sort then
Your code that you shared is totally OK, here is the working example:
var arr = [
{name: 'b'},
{name: 'a'},
{name: 'x'},
{name: 'i'},
{name: 'l'}
]
arr.sort(function(a, b) {
var x = a.name.toLowerCase(),
y = b.name.toLowerCase();
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
console.log(arr)
For more info about sort
: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
May be the issue is somewhere else, in code, which you didn't share.
Get object values in an array and sort.
const viewsArr = Object.values(views)
.sort((a, b) => a.name.lowerCase() > b.name.lowerCase());
This is not exact code but in your you are not getting groups..
let groups = Object.keys(data)
.map(group => {
let records = Object.values(data[group])
.map(record => ({
name: record.name,
group,
}));
return records;
});
groups = [].concat(...groups);
return groups.sort((a, b) => {
return a.name.localeCompare(b.name);
});