how to sort the name in array list by alphabet in javascript, I tried with this code
const sample = [
{
name: "AddMain",
mesg: "test000"
},
{
name: "Ballside",
mesg: "test004545"
},
{
name: "TestMain",
mesg: "test00"
},
{
name: "ball",
mesg: "test004545"
},
{
name: "Main",
mesg: "test004545"
},
{
name: "alliswell",
mesg: "test004545"
}
]
sample.sort(sortBy('name', false, function(a){return a.toUpperCase()}));
but it not working properly in this code sortBy I am using lodash. if it possible in lodash it will to fine
DEMO
const sample = [
{
name: "AddMain",
mesg: "test000"
},
{
name: "Ballside",
mesg: "test004545"
},
{
name: "TestMain",
mesg: "test00"
},
{
name: "ball",
mesg: "test004545"
},
{
name: "Main",
mesg: "test004545"
},
{
name: "alliswell",
mesg: "test004545"
}
];
var chars =_.orderBy(sample, [user => user.name.toLowerCase()], ['asc']);
console.log(chars);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
According to the lodash docs the API of sortBy
is:
_.sortBy(collection, [iteratees=[_.identity]])
In your case, the collection
is your sample
array and your [iteratees=[_.identity]]
should be a function or an array which returns the key you want to sort.
So this is probably what you were going for:
_.sortBy(sample, ['name']);
OR
_.sortBy(sample, function(o){return o.name;}]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With