Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sortby the name by alphabet in array list using lodash

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

like image 543
techie18 Avatar asked Jan 02 '23 11:01

techie18


2 Answers

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>
like image 152
Sajeetharan Avatar answered Jan 05 '23 16:01

Sajeetharan


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

like image 30
Chirag Ravindra Avatar answered Jan 05 '23 16:01

Chirag Ravindra