-2

I have an array of objects like this:

[{"name" : "Annie", "number" : 25},
{"name" : "Zeus", "number" : 25},
{"name" : "John", "number" : 40},
{"name" : "John", "number" : 32},
{"name" : "Zeus", "number" : 75},
{"name" : "Zeus", "number" : 32} ]

I would like to filter this such that I have one instance of each unique name and that instance must give me the largest number less than or equal to 40. The above case, if filtered, would return:

[{"name" : "Annie", "number" : 25},
{"name" : "John", "number" : 40},
{"name" : "Zeus", "number" : 32} ]

The final array does not have to be sorted in any particular order.

docwelch
  • 3
  • 2
  • 1
    You should add the code you've tried. – Andy May 09 '16 at 01:24
  • 1
    Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a Minimal, Complete, and Verifiable example. –  May 09 '16 at 01:25
  • You should probably loop over the array with *filter* and create an index object of the *names* encountered. Keep the first of each with a value <= 40 and if duplicates are found, keep the one with the highest value <= 40. What have you tried? – RobG May 09 '16 at 01:26

1 Answers1

0

It's a pretty simple challenge with an O(N) solution. A function do so so would be this:

function solution(A)
{
    var endObj = {};
    for (var i=0, ii=A.length; i<ii; i++)
    {
        var val = A[i];

        if (val.number > 40)
            continue;

        if (!endObj[val.name]) {
            endObj[val.name] = val;
            continue;
        }

        if (endObj[val.name].number < val.number)
            endObj[val.name] = val;
    }

    var endArr = [];
    for (var key in endObj)
        endArr.push(endObj[key]);

    return endArr;
}

I just tracked the names by using them as the key to a new object, then convert that object to a keyless Array once finished.

JSfiddle example here: https://jsfiddle.net/qa7vzvp5/

BryanGrezeszak
  • 577
  • 2
  • 8