Ashim Ashim - 3 years ago 252
Javascript Question

Find max and min from a object in javascript only

Hi I have an array like below....

dataArray(7)[
{dataIndex: 0, specialEventID: 65268}
1
:
{dataIndex: 1, specialEventID: 65268}
2
:
{dataIndex: 1, specialEventID: 65271}
3
:
{dataIndex: 1, specialEventID: 65272}
4
:
{dataIndex: 2, specialEventID: 65270}
5
:
{dataIndex: 5, specialEventID: 65269}
6
:
{dataIndex: 6, specialEventID: 65269}
]


Now I want max and min index of every specialEventID
Like 65268['max':1, 'min':0]

65271['max':1, 'min':1] //because only one object for 65271
65272['max':1, 'min':1] //because only one object for 65272
65270['max':2, 'min':2]//because only one object for 65270
65270['max':5, 'min':6]


Can anyone please help me to find the max and min index like above?
Thanks in advance.

Answer Source

You could take an object for the result, where specialEventID acts as key and an object for min and max values.

var data = [{ dataIndex: 0, specialEventID: 65268 }, { dataIndex: 1, specialEventID: 65268 }, { dataIndex: 1, specialEventID: 65271 }, { dataIndex: 1, specialEventID: 65272 }, { dataIndex: 2, specialEventID: 65270 }, { dataIndex: 5, specialEventID: 65269 }, { dataIndex: 6, specialEventID: 65269 }],
    result = {};

data.forEach(function (o) {
    if (!result[o.specialEventID]) {
        result[o.specialEventID] = { min: o.dataIndex, max: o.dataIndex };
        return;
    }
    if (result[o.specialEventID].min > o.dataIndex) {
        result[o.specialEventID].min = o.dataIndex;
        return;
    }
    if (result[o.specialEventID].max < o.dataIndex) {
        result[o.specialEventID].max = o.dataIndex;
    }
});
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download