1

I have a data like this format.

    var data = [
       {id:1,
        format:'txt',
        array1:[
                {id:10, txt:3, Nm:A},
                {id:100, txt:2, Nm:B},
                {id:1000, txt:1, Nm:C}
               ]
       },
       {id:2,
        format:'vidz',
        array1:[
                {id:10,txt:5,Nm:X},
                {id:100,txt:9,Nm:Y},
                {id:1000,txt:6,Nm:Z}
               ]
       }
       ]

need to sortby "txt" using underscoreJs or any javascript method

var data = [
           {id:1,
            format:'txt',
            array1:[
                    {id:1000, txt:1, Nm:C},
                    {id:100, txt:2, Nm:B},
                    {id:10, txt:3, Nm:A}
                   ]
           },
           {id:2,
            format:'vidz',
            array1:[
                    {id:10,txt:5,Nm:X},
                    {id:1000,txt:6,Nm:Z},
                    {id:100,txt:9,Nm:Y}

                   ]
           }
           ]

How to sortBy ascending order for the "txt" inside of array1

2
  • 1
    have the arrays inside really different names? Commented May 27, 2017 at 6:48
  • It is an example format @NinaScholz Commented May 27, 2017 at 6:51

1 Answer 1

1

You could use plain javascript an iterate the array and take then the inner array for sorting.

var data = [{ id: 1, format: 'txt', array1: [{ id: 10, txt: 3, Nm: 'A' }, { id: 100, txt: 2, Nm: 'B' }, { id: 1000, txt: 1, Nm: 'C' }] }, { id: 2, format: 'vidz', array1: [{ id: 10, txt: 5, Nm: 'X' }, { id: 100, txt: 9, Nm: 'Y' }, { id: 1000, txt: 6, Nm: 'Z' }] }];

data.forEach(a => a.array1.sort((a, b) => a.txt - b.txt));

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.