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;}]);
Your code should be like:
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" }]; let result = _.sortBy(sample, ({name}) => name.toLowerCase()); console.log(result);
.as-console-wrapper {max-height: 100% !important;top: 0;}
<script src="//lodash.com/vendor/cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>
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 result = sample.slice().sort((a,b) => a.name.localeCompare(b.name, undefined, {numeric: true})); console.log(result);
const characters = [ { name: 'Jean-Luc Picard', age: 59 }, { name: 'William Riker', age: 29 }, { name: 'Deanna Troi', age: 28 }, { name: 'Worf', age: 24 } ]; // Sort characters by the `age` property const sorted = _.sortBy(characters, 'age'); console.log(sorted); sorted[0].name; // Worf sorted[1].name; // Deanna Troi sorted[2].name; // William Riker sorted[3].name; // Jean-Luc Picard
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.core.js"></script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.