简体   繁体   中英

Sorting array based on key using Lodash

I have an array which looks like:

let arr = [{
    tcode:1,
    tarray:[{tcode:3},{tcode:2},{tcode:1}]
},{
   tcode:1,
    tarray:[{tcode:3},{tcode:2},{tcode:1}] 
}]

Now I want to sort the inner arr such that for each object, tarray should always contain the first object with tarray.tcode = outer tcode. What is the best way to achieve this using lodash?

You need to first map main array and then use sortBy .

_.map(arr, function(x){
   return _.sortBy(x.tarray, "tcode")
})

after that check arr and you will get sorted array of tarray

 const arr = [{ tcode:1, tarray:[{tcode:3},{tcode:2},{tcode:1}] },{ tcode:1, tarray:[{tcode:3},{tcode:2},{tcode:1}] }] const result = _.map(arr, function(x){ return _.sortBy(x.tarray, "tcode") }) console.log(result);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM