Chin
Chin

Reputation: 12712

Reorder Collection with underscore

I'm new to underscore so pardon my ignorance.

Is there a quick and easy way to do the following:

men:{gerald:{"name":"Gerald", "age":50},mike:{"name":"Mike", "age":50},charles:{"name":"Charles", "age":50}}

Where name is Mike - set at position 1 (index 0)

I just want to shuffle the items so the first item is set by the name I choose.

Any help more than welcome.

Upvotes: 0

Views: 1399

Answers (2)

Eric
Eric

Reputation: 97641

You don't need underscore.js. Array.sort will do fine:

myJson.men.sort(function(a, b) { return b.name == "Mike" })

This isn't really model usage of sort, but it does the job.


Also, your JSON is invalid. You need square brackets around the array, not curlies:

{
    "men": [{
        "name": "Gerald", "age": 50
    },{
        "name": "Mike", "age": 50
    },{
        "name": "Charles", "age": 50
    }]
}


Edit:

You can't "order" that JSON. What you're asking to do is order an associative array. This doesn't make any sense. If order of items is important, you want an array, not an object.

Upvotes: 0

pimvdb
pimvdb

Reputation: 154918

Since _.suffle shuffles all elements, you'd need to splice out all elements but the predefined one, shuffle them, and concatenate the shuffled elements to an existing array which contains the predefined element.

Something like:

var orig = [1, 2, 3, 4, 5],
    shuffled = [];

shuffled[0] = orig[2]; // 3 is the predefined element

shuffled = shuffled.concat( _.shuffle( orig.slice(0,2).concat( orig.slice(3) ) ) );

which gets the array without the predefined element, shuffles it, and concatenates it to the shuffled array, which contains the predefined variable as its first element.

Upvotes: 1

Related Questions