javascriptfunctiones6-promise

Get maximum greater key values with object of array


I want the maximum key of an object into an array in Javascript, the following is the example of an array of JSON. I tried with reduce() ES6 function, but it will return only on record, So please help me to get maximum no. of key array, i provide also output what i want, It will be great if the solution in high order functions(ES6)

let arr = [{
                key : 1,
                name : 'testaa',
                dept : 'ggg'
            }, {
                key : 1,
                name : 'testaa',
                dept : 'ggg'
            }, {
                key : 2,
                name : 'testaa',
                dept : 'ggg'
            }, {
                key : 2,
                name : 'testaa',
                dept : 'ggg'
            }, {
                key : 2,
                name : 'testaa',
                dept : 'ggg'
            }, {
                key : 3,
                name : 'testaa',
                dept : 'ggg'
            }, {
                key : 3,
                name : 'testaa',
                dept : 'ggg'
            }]

 output i want maximum key of array:


    arr = [{
                key : 3,
                name : 'testaa',
                dept : 'ggg'
            }, {
                key : 3,
                name : 'testaa',
                dept : 'ggg'
            }]

I tried with reduce function but getting only one records

let data = myArray.reduce(function(prev, curr) {
    return prev.key > curr.key ? prev : curr;
});

Solution

  • You were only returning the last higher key. You have to build an array containing all the elements that have the higher key.

    In my algorithm, I store the highest key in an array, when I encounter an element with an higher key than the elements that I stored, I wipe the array and recreate one.

    const arr = [{
      key: 1,
      name: 'testaa',
      dept: 'ggg'
    }, {
      key: 1,
      name: 'testaa',
      dept: 'ggg'
    }, {
      key: 2,
      name: 'testaa',
      dept: 'ggg'
    }, {
      key: 2,
      name: 'testaa',
      dept: 'ggg'
    }, {
      key: 2,
      name: 'testaa',
      dept: 'ggg'
    }, {
      key: 3,
      name: 'testaa',
      dept: 'ggg'
    }, {
      key: 3,
      name: 'testaa',
      dept: 'ggg'
    }];
    
    const higherKey = arr.reduce((tmp, x) => {
      if (!tmp.length || tmp[0].key < x.key) {
        return [x];
      }
    
      if (tmp[0].key === x.key) {
        tmp.push(x);
      }
    
      return tmp;
    }, []);
    
    console.log(higherKey);