-2

Lets say we have the following:


let x = [
{"color": "blue", "cat": "eec" },
{"color": "red", "cat": "vbs" },
{"color": "black", "cat": "asd" },
]

how can I sort this by cat? so that I can then do something like

let y = sorted.asd.color;

or 

y = sorted[asd][color];

note: cat is unique

Thanks

9
  • What have you tried? Hint - you'll use array.sort and localeCompare - look those up and if you get stuck in your attempt, come back to ask for help Commented Apr 15, 2022 at 18:56
  • 2
    the array method .sort can take a function Commented Apr 15, 2022 at 18:57
  • Does this answer your question? Group a Javascript Array Commented Apr 15, 2022 at 18:59
  • 1
    OP probably want to group by or something like this instead of sorting, but it's hard to understand xyproblem.info Commented Apr 15, 2022 at 19:00
  • 1
    @asyncawait Please post this as an answer. I'd like to see what happens. Commented Apr 15, 2022 at 19:11

2 Answers 2

2

You can use .reduce:

let x = [
{"color": "blue", "cat": "eec" },
{"color": "red", "cat": "vbs" },
{"color": "black", "cat": "asd" },
]

const sorted = x.reduce((acc, el) => {
  acc[el.cat] = el;
  return acc;
}, {});

const y = sorted.asd.color;

console.log(y);

or .map and Object.entries:

let x = [
{"color": "blue", "cat": "eec" },
{"color": "red", "cat": "vbs" },
{"color": "black", "cat": "asd" },
]

const sorted = Object.fromEntries(x.map(el => [el.cat, el]));

const y = sorted.asd.color;

console.log(y);

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

Comments

2

You could try something like this:

const x = [
    {"color": "blue", "cat": "eec" },
    {"color": "red", "cat": "vbs" },
    {"color": "black", "cat": "asd" },
]

function sortByCat(array) {
    let cats = {};
    for (let i = 0; i < array.length; i++) {
        let currentObject = array[i];
        cats[currentObject.cat] = currentObject;
    }

    return cats;
}

let sorted = sortByCat(x);

let y = sorted.asd.color;
y = sorted['asd']['color'];

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.