krystof18
krystof18

Reputation: 247

Sorting JSON object by value of bool in JavaScript

I'm new to JavaScript and I'm trying to work with JSON object I got from an API and I'm trying to find a way how to sort it by bool value inside. I had a feeling that this will be already answered the question, but I can't find a way to do it my way.

Here is my response (It's my API so I can change data types and add values if needed)

[
    {
        "name":"Name 1",
        "photoUrl":"Photo url 1",
        "bool": false
    },
    {
        "name":"Name 2",
        "photoUrl":"Photo url 2",
        "bool": false
    },
    {
        "name":"Name 3",
        "photoUrl":"Photo url 3",
        "bool": true
    },
    {
        "name":"Name 4",
        "photoUrl":"Photo url 4",
        "bool": false
    },
    {
        "name":"Name 5",
        "photoUrl":"Photo url 5",
        "bool": true
    }
]

I want to have objects with bool: true on top, and those with bool: false on bottom. I couldn't find a way to do it myself. I appreciate any help.

Upvotes: 1

Views: 490

Answers (3)

atiq1589
atiq1589

Reputation: 2327

First, deconstruct the API response in key-value with Object.entries. sort the value by bool and then construct the sorted result with reduce

const obj = {
    "0":{
        "name":"Name 1",
        "photoUrl":"Photo url 1",
        "bool": false
    },
    "1":{
        "name":"Name 2",
        "photoUrl":"Photo url 2",
        "bool": false
    },
    "2":{
        "name":"Name 3",
        "photoUrl":"Photo url 3",
        "bool": true
    },
    "3":{
        "name":"Name 4",
        "photoUrl":"Photo url 4",
        "bool": false
    },
    "4":{
        "name":"Name 5",
        "photoUrl":"Photo url 5",
        "bool": true
    }
}

const sorted = Object.entries(obj).sort( ([a_k, a_v], [b_k, b_v]) => b_v.bool - a_v.bool).reduce((acc, curr, idx) => Object.assign(acc, {[idx]: curr[1]}), {});
console.log(sorted);

UPDATED

const list = [
    {
        "name":"Name 1",
        "photoUrl":"Photo url 1",
        "bool": false
    },
    {
        "name":"Name 2",
        "photoUrl":"Photo url 2",
        "bool": false
    },
    {
        "name":"Name 3",
        "photoUrl":"Photo url 3",
        "bool": true
    },
    {
        "name":"Name 4",
        "photoUrl":"Photo url 4",
        "bool": false
    },
    {
        "name":"Name 5",
        "photoUrl":"Photo url 5",
        "bool": true
    }
];
list.sort((a,b) => b.bool - a.bool);
console.log(list);

Upvotes: 2

MonkeyScript
MonkeyScript

Reputation: 5121

You can use Array.prototype.sort(),

array.sort(function(a,b){return b.bool-a.bool});

console.log(array);

If you want the reverse order,

array.sort(function(a,b){return a.bool-b.bool});

Upvotes: 2

Andy
Andy

Reputation: 525

this is what you need:

[...].sort(a => a.bool ? -1 : 1)

-1 will put all your objects at the beginning of your array where 'bool' is true

Upvotes: 2

Related Questions