0

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"] ?

0

4 Answers 4

2

To get your desired Array, you can use:

Stuffs.map(({ name }) => name).sort();
Sign up to request clarification or add additional context in comments.

1 Comment

This worked too. Thanks!
0

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

Comments

0

Using chai

assert.deepInclude(Stuffs, {name: "AVE"});
assert.deepInclude(Stuffs, {name: "NSA"});
assert.deepInclude(Stuffs, {name: "QRE"});
assert.deepInclude(Stuffs, {name: "PWE"});

Edit: I may have misunderstood it to mean, how can assert that the array has those values.

Comments

0

First you would need a sorted array to compare it to. The original array needs to be cloned (shallow is fine for this) since sort will modify the array it is called on. Using from to generate the clone, we can then alphabetically sort the new array to get the desired order.

const sortedStuffs = Array.from(stuffs).sort(({name: a}, {name: b}) => a.localeCompare(b));

Finally using every, we can compare the names for each element to see if they match. As soon as one fails, the returned value will be false

stuffs.every(({name}, i) => name === sortedStuffs[i].name);

Full working example:

const stuffs = [
 {name: "PWE", address: "1234567890"},
 {name: "NSA", address: "1234567890"},
 {name: "AVE", address: "1234567890"},
 {name: "QRE", address: "1234567890"}
];

const sortedStuffs = Array.from(stuffs).sort(({name: a}, {name: b}) => a.localeCompare(b));

const isSorted = stuffs.every(({name}, i) => name === sortedStuffs[i].name);

console.log(isSorted);

7 Comments

Thanks. But this returns true.
@evee It returns false for me. What browser did you run the code on?
Ah, right. Its returns false, sorry.
@eevee I am a bit confused. Were you asking how to assert if the array is ordered by the name of the elements or just how to get a new array of just the sorted names?
I'm trying to assert the sorted array. N. Jadhav and Dan's answer helped. :)
|