katie hudson
katie hudson

Reputation: 2893

Ordering array in defined order

I have tried several answers on SO but nothing seems to work. I am processing some data and placing it onto an array. To do this I have the following

let aggData = [];

for (let i = 0; i < data.length; i++) {
    let flag = data[i]['Category'].replace(/[_]/g, " ");
    flag = flag.toLowerCase()
        .split(' ')
        .map((s) => s.charAt(0).toUpperCase() + s.substring(1))
        .join(' ');

    aggData.push({
        "Flag": flag,
        "Freq": data[i]['Count']
    });
}
console.log( JSON.stringify( aggData ) );

The above outputs the following

[
    {"Flag":"Four","Freq":123},
    {"Flag":"One","Freq":234},
    {"Flag":"Three","Freq":345},
    {"Flag":"Two Days","Freq":456}
]

So it looks like it is naturally ordering it based on Alphabetical order. I need it to be in an order I define, more specifically this

let order = ["Three", "One", "Two Days", "Four"];

let arr = aggData.sort(function(a,b) {
    return order.indexOf( a.key ) > order.indexOf( b.key );
});

console.log( 'Ordered: ', JSON.stringify( arr ) );

The above is returning the exact same order as before though. How can I get it ordered the way I require?

Thanks

Upvotes: 0

Views: 42

Answers (2)

baao
baao

Reputation: 73211

All you need to do is to use sort correctly, returning a number instead of a boolean... And of course using the right property...

let data = [
    {"Flag":"Four","Freq":123},
    {"Flag":"One","Freq":234},
    {"Flag":"Three","Freq":345},
    {"Flag":"Two Days","Freq":456}
]


let order = ["Three", "One", "Two Days", "Four"];

let arr = data.sort(function(a,b) {
    return order.indexOf( a.Flag ) - order.indexOf( b.Flag );
});

console.log( 'Ordered: ', JSON.stringify( arr ) );

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386520

You need to get the right property Flag and take the delta instead of a boolean value.

BTW, Array#sort mutates the array.

var aggData = [{ Flag: "Four", Freq: 123 }, { Flag: "One", Freq: 234 }, { Flag: "Three", Freq: 345 }, { Flag: "Two Days", Freq: 456 }],
    order = ["Three", "One", "Two Days", "Four"];

aggData.sort(function (a, b) {
    return order.indexOf(a.Flag) - order.indexOf(b.Flag);
});

console.log(aggData);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 2

Related Questions