subhra subhra - 2 months ago 6
Javascript Question

How to sort array as per key value using Angular.js/Javascript

I need one help. I need to sort an array as per key value with one specific format using Angular.js/Javascript.I am explaining my array below.

var stepsModel=[
{'day_id':2,'day_name':'Tuesday','image':"1.png"},
{'day_id':2,'day_name':'Tuesday','image':"2.png"},
{'day_id':2,'day_name':'Tuesday','image':"3.png"},
{'day_id':3,'day_name':'Wednsday','image':"1.png"},
{'day_id':3,'day_name':'Wednsday','image':"2.png"}
]


The above is my given array.i need to sort it as per the
day_id
.My expected output is given below.

var output = [
{
'day_id': 2,
'day_name': 'Tuesday',
'special': [
{ 'image': 1. png },
{ 'image': 2. png },
{ 'image': 3. png }
]
},
{
'day_id': 3,
'day_name': 'Wednsday',
'special': [
{ 'image': 1. png },
{ 'image': 2. png }
]
}
]


Please help me to sort the given array and get the result like above.

Answer

You could use a hash table for the right assignment of the images to the days.

Optional, you could use Array#reduce instead of Array#forEach, if you like to use a compact style.

var stepsModel = [
    { 'day_id': 2, 'day_name': 'Tuesday', 'image': "1.png" },
    { 'day_id': 2, 'day_name': 'Tuesday', 'image': "2.png" },
    { 'day_id': 2, 'day_name': 'Tuesday', 'image': "3.png" },
    { 'day_id': 3, 'day_name': 'Wednsday', 'image': "1.png" },
    { 'day_id': 3, 'day_name': 'Wednsday', 'image': "2.png" }
];
var grouped = [];

stepsModel.forEach(function(a) {
    if (!this[a.day_id]) {
        this[a.day_id] = { day_id: a.day_id, day_name: a.day_name, special: [] };
        grouped.push(this[a.day_id]);
    }
    this[a.day_id].special.push({ image: a.image });
}, Object.create(null));

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