skip to Main Content

I have an array of objects like below, and I would like to sort the array by value of each object.


const arr = [
        {
            0: "id1",
            1: {
                title: "object1",
                value: 200
            }
        },
        {
            0: "id2",
            1: {
                title: "object2",
                value: 100
            }
        },
        {
            0: "id3",
            1: {
                title: "object3",
                value: 300
            }
        },
    ]


//result - array I want to get as the final result of sort
sortedArr = [
        {
            0: "id3",
            1: {
                title: "object2",
                value: 100
            }
        },
        {
            0: "id2",
            1: {
                title: "object1",
                value: 200
            }
        },
        {
            0: "id3",
            1: {
                title: "object3",
                value: 300
            }
        },
    ]

I tried:

    const sortedArr = arr.sort((a, b) => {
        if (a[1].value - b[1].value) {
            return -1
        } else {
            return 1
        }             
    })

But I only get the reversed array not sorted as I wish.

I found similar problems but when I tried other solutions it didn’t work for me, or I did something wrong.

2

Answers


  1. You’re misusing data formats I think. Objects are not a replacement for Arrays where keys have to be indexed 0, 1
    Anyways:

    const arr = [
      {
        0: "id1",
        1: {title: "object1",value: 200}
      },
      {
        0: "id2",
        1: {title: "object2",value: 100}
      },
      {
        0: "id3",
        1: {title: "object3",value: 300}
      },
    ];
    
    const sortStrangeInputDataByValue = (a, b) => a["1"].value - b["1"].value;
    const sorted = arr.sort(sortStrangeInputDataByValue);
    console.log(sorted);

    A far better data input given a well structured array of items objects would be:

    const arr = [
      {id: "id1", title: "object1", value: 200},
      {id: "id2", title: "object2", value: 100},
      {id: "id3", title: "object3", value: 300}
    ];
    
    
    const sortByValue = (a, b) => a.value - b.value;
    const sorted = arr.sort(sortByValue);
    console.log(sorted);
    Login or Signup to reply.
  2. Interesing!

    What do you think about my code:

    const sortedArr = arr.sort((a, b) => a[1].value > b[1].value - 1);

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search