0

I'm trying to get a multi-array / nested map sorted by value via JavaScript / TypeScript.

My array currently looks like this:

let array =
    [
      {
        classification: {
          company_id: 1
        },
        information: {
          name: 'C'
        }
      },
      {
        classification: {
          company_id: 1
        },
        information: {
          name: 'B'
        }
      },
      {
        classification: {
          company_id: 1
        },
        information: {
          name: 'A'
        }
      }
    ];

Now I'd like to sort by the ['information']['name'] values like this:

let array_sorted =
    [
      {
        classification: {
          company_id: 1
        },
        information: {
          name: 'A'
        }
      },
      {
        classification: {
          company_id: 1
        },
        information: {
          name: 'B'
        }
      },
      {
        classification: {
          company_id: 1
        },
        information: {
          name: 'C'
        }
      }
    ];

Does anybody know how to do that? I'm especially struggling with the nested stuff...

Thank you in advance!

2 Answers 2

2

Using String.prototype.localeCompare, you can compare the string values and based on that result, using Array.prototype.sort function, you can sort the arrays as follows.

let array = [{
    classification: {
      company_id: 1
    },
    information: {
      name: 'C'
    }
  },
  {
    classification: {
      company_id: 1
    },
    information: {
      name: 'B'
    }
  },
  {
    classification: {
      company_id: 1
    },
    information: {
      name: 'A'
    }
  }
];

const result = array.sort((a, b) => a.information.name.localeCompare(b.information.name));
console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

0

You can use the sort function. It would look like this:

const array_sorted = array.sort(
  (a, b) => {
    if (a > b.information.name) return -1;
    if (a < b.information.name) return 1;
    return 0;
  }, 0
)

You can invert the order by swapping the 1 and the -1. The sort function takes the first parameter of a function that returns -1, 1 or 0 which denotes the order and a second parameter that sets the initial value of variable 'a' (optional). I have set the initial value to 0, that's just how I like to use the sort function as I think it makes it easier to write :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.