Search code examples
javascriptsortingchaiassertionskarma-mocha

Assert sorted array of objects


I'm doing unit testing using javascript testing framework (mocha, chai, etc). How can I assert my array of objects using its name?

I can successfully sort this using localeCompare but I'm not getting what I wanted on my test. It just returns 1 or -1.

Here's my a sample of what I want to sort.

var Stuffs = [
     { name: "PWE", address: "1234567890" },
     { name: "NSA", address: "1234567890" },
     { name: "AVE", address: "1234567890" },
     { name: "QRE", address: "1234567890" },
  ]

How can I assert this to ["AVE", "NSA", "PWE", "QRE"] ?


Solution

  • You could also use reduce() method of array and then sort().

    DEMO

    var Stuffs = [{ name: "PWE", address: "1234567890" },
         { name: "NSA", address: "1234567890" },
         { name: "AVE", address: "1234567890" },
         { name: "QRE", address: "1234567890" }];
         
    let sortedArr = Stuffs.reduce((r,{name})=>r.concat(name),[]).sort((a,b)=>a.localeCompare(b));
    
    console.log(sortedArr);