1
\$\begingroup\$

Wherever the biggest number is always use the 'big' value

If another number is equal to that number, use the 'big' value

Set the next number in line to 'medium'

If another number is equal to that number, use the 'medium' value

Set the next number in line to 'small'

If another number is equal to that number, use the 'small' value

entries: any { "FirstNames": 6, "Names": 8, "": 6, "Locations": 3, "Others": 2};

let sorted = this.sortByValues(this.entries);

var obj = {};
for (var i = 0; i <= sorted.length; i++) {
    if (Object.keys(obj).length === 0 && obj.constructor === Object)
        obj[sorted[i]] = "big";
    else if (this.entries[sorted[i]] == this.entries[sorted[i-1]] && obj[sorted[i-1]] == "big")
        obj[sorted[i]] = obj[sorted[i-1]];
    else if(this.entries[sorted[i]] < this.entries[sorted[i-1]] && obj[sorted[i-1]] == "big")
        obj[sorted[i]] = "medium";
    else if(this.entries[sorted[i]] == this.entries[sorted[i-1]] && obj[sorted[i-1]] == "medium")
        obj[sorted[i]] = obj[sorted[i-1]];
    else if(this.entries[sorted[i]] < this.entries[sorted[i-1]] && obj[sorted[i-1]] == "medium")
        obj[sorted[i]] = "small";
    else if(this.entries[sorted[i]] == this.entries[sorted[i-1]] && obj[sorted[i-1]] == "small")
        obj[sorted[i]] = obj[sorted[i-1]];
    else
        obj[sorted[i]] = obj[sorted[i-1]];
}

sortByValues(list : any)
{
    return Object.keys(list).sort(function(a,b){return list[a]-list[b]}).reverse());
}
\$\endgroup\$
2
  • \$\begingroup\$ What should happen if there are lots of values e.g. 100, 99, 98, ... 1 ? \$\endgroup\$ – wOxxOm Sep 29 '16 at 10:41
  • \$\begingroup\$ @wOxxOm 100 - big , 99 - medium, 98-1 - small \$\endgroup\$ – Dimitri Sep 29 '16 at 10:44
1
\$\begingroup\$

Only two values of the sorted array are needed to decide the resultant tags, so the algo is:

  1. scan all entries and find the maximum and pre-maximum.
  2. scan all entries and tag them accordingly in a new object

Tests show 10x speed-up, but of course it's noticeable only on large number of repetitions.

tagValues(data : any) {
    let keys = Object.keys(data);
    let len = keys.length;
    let max = -Infinity, max2 = -Infinity;
    for (let i = 0; i < len; i++) {
        let value = data[keys[i]];
        if (value > max) {
            max2 = max;
            max = value;
        }
    }
    let tagged = {};
    for (let i = 0; i < len; i++) {
        let key = keys[i];
        let value = data[key];
        tagged[key] = value === max ? 'big' : value === max2 ? 'medium' : 'small';
    }
    return tagged;
}

P.S. As for sortByValues, instead of reversing an array after sorting it, invert the comparison.

\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.