0

I'm sure there is a way to do this, but I am having a little trouble getting it working. I basically have an Object Array that is organized like:

-0
--key: "john"
--value:
---0: "some string"
---1: "some other string"
-1
--key: "julie"
--value:
---0: "some string"
---1: "some other string"
-2
--key: "jane"
--value:
---0: "some string"
---1: "some other string"

Note that I just put some string and some other string. These are actually different strings.

I would like to sort this object according to the first entry in the value array. I have already sorted the value array before pushing to the object.

I create the above object by doing something like this:

var userData = [];
userMessage.sort()
userData.push({
    key: 'kate',
    value: ['Please call Dan Smith', 'Sorry this is incorrect']
});
userData.push({
    key: 'john',
    value: ['Please call Dan Smith', 'You did not provide the correct info']
});
userData.push({
    key: 'dave',
    value: ['Sorry this is incorrect', 'You did not provide correct information']
})

I have a lot of different possbile messages and users this is just an example. What I would expect be outputted would be basically be all the users with Please call Dan Smith in userMessage[0] would be lumped together and those that have Sorry this is incorrect```` inuserMessage[0]``` would be lumped together. I do not care about the order of the keys.

userData = [
    'kate': ['Please call Dan Smith', 'Sorry this is incorrect'],
    'john': ['Please call Dan Smith', 'You did not provide the correct info'],
    'dave': ['Sorry this is incorrect', 'You did not provide correct information']
]

I know how to do this for keys or even for values, but what is tricky is the fact that I have an array for the value.

Any suggestions?

  • 2
    Please post **complilable** input and expected output. It's not possible to copy this to create an answer or snippet. And it's hard to understand which item you are referring to when you say *"this object"* or *this array*. Please read the [Stack Overflow question checklist](https://meta.stackoverflow.com/questions/260648) – adiga Jul 19 '19 at 18:07
  • 1
    Amount of effort to type that as valid code would have been the same as the invalid version you entered....which can't be used in anything and isn't really clear what actual structure is. Beyond that it's not really clear what you want sorted – charlietfl Jul 19 '19 at 18:09
  • 1
    Wasn't intended to be rude....was just being truthful. Please take a few minutes to read [mcve] Your pseudo code is hard to interpret...literal code isn't – charlietfl Jul 19 '19 at 18:25
  • 1
    You probably need this: `userData.sort((a, b) => a.value[0].localeCompare(b.value[0]))` – adiga Jul 19 '19 at 18:29
  • Perfect thank you @adiga! Worked. – new_programmer_22 Jul 19 '19 at 18:37

0 Answers0