user5443928
user5443928

Reputation:

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.

Upvotes: 2

Views: 57

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386604

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; }

Upvotes: 2

Łukasz Trzewik
Łukasz Trzewik

Reputation: 1165

You can use reduce function for it to create an object that acts like dictionary and then call a map function on it's keys like this:

var groupedDays = stepsModel.reduce((steps, step) => {
    if (!steps[step.day_id])
        steps[step.day_id] = ({ day_id: step.day_id, day_name: step.day_name, special: [] })

    steps[step.day_id].special.push({image: step.image})
    return steps
}, {});

var output = Object.keys(groupedDays).map(k => groupedDays[k])

Upvotes: 1

Related Questions