Reputation: 159
I have to create my customized grouping order based on standardID
in the following array of objects:
Actual Array:
var test=[
{ID: "91",Name: "sgtue", standardID: "1"},
{ID: "41",Name: "asdfasdf", standardID: "2"},
{ID: "5", Name: "credd", standardID: "2"},
{ID: "2",Name: "dddawer", standardID: "2"},
{ID: "2",Name: "dsfadf", standardID: "3"},
{ID: "275", Name: "xcvcvc", standardID: "201"}
]
Expected Result: I Simply want to group the standardID
's like 1,3,2,2,2,201
[
{ID: "91",Name: "sgtue", standardID: "1"},
{ID: "2",Name: "dsfadf", standardID: "3"},
{ID: "275", Name: "xcvcvc", standardID: "201"},
{ID: "41",Name: "asdfasdf", standardID: "2"},
{ID: "5", Name: "credd", standardID: "2"},
{ID: "2",Name: "dddawer", standardID: "2"}
]
Kindly help me to sort out the problem.
Upvotes: 0
Views: 78
Reputation: 1866
It's pure javascript and this will "sort" it your way, define your sort order in groupOrder variable:
var groupOrder = [1,3,201,2];
var testSorted = test.sort((a, b) => groupOrder.indexOf(parseInt(a.standardID))-groupOrder.indexOf(parseInt(b.standardID)));
Fiddle:
https://jsfiddle.net/pLe44x1x/1/
Upvotes: 0
Reputation: 22776
You can use JavaScript's sort
function with your own criteria (map):
var test = [
{ID: "91",Name: "sgtue", standardID: "1"},
{ID: "41",Name: "asdfasdf", standardID: "2"},
{ID: "5", Name: "credd", standardID: "2"},
{ID: "2",Name: "dddawer", standardID: "2"},
{ID: "2",Name: "dsfadf", standardID: "3"},
{ID: "275", Name: "xcvcvc", standardID: "201"}
];
var myMap = {
"1": 0,
"3": 1,
"2": 2
};
test.sort((a, b) => myMap[a.standardID[0]] - myMap[b.standardID[0]]);
console.log(test);
Upvotes: 0
Reputation:
You can try this prototype custom sorting by attributes objects :
var test=[{ID: "91",Name: "sgtue", standardID: "1"},
{ID: "41",Name: "asdfasdf", standardID: "2"},
{ID: "5", Name: "credd", standardID: "2"},
{ID: "2",Name: "dddawer", standardID: "2"},
{ID: "2",Name: "dsfadf", standardID: "3"},
{ID: "275", Name: "xcvcvc", standardID: "201"}
];
https://codepen.io/anon/pen/KXNpMZ?editors=1112
@Sathish
UPDATED in ordered by indexes array reference here :
https://codepen.io/anon/pen/RLoZOX?editors=1112
Upvotes: 1
Reputation: 16997
var test = [{
ID: "91",
Name: "sgtue",
standardID: "1"
},
{
ID: "41",
Name: "asdfasdf",
standardID: "2"
},
{
ID: "5",
Name: "credd",
standardID: "2"
},
{
ID: "2",
Name: "dddawer",
standardID: "2"
},
{
ID: "2",
Name: "dsfadf",
standardID: "3"
},
{
ID: "275",
Name: "xcvcvc",
standardID: "201"
}
];
// parseInt used because of your input datatype
var sortOrder = [1,3,2,201];
var out = test.sort(function(a, b) {
return sortOrder.indexOf(parseInt(a.standardID)) - sortOrder.indexOf(parseInt(b.standardID));
});
//sorted
console.log(out)
Upvotes: 0