0

I have an object function that turns my array into an object with a key and value.

function toObject(arr) {
    var obj = {};
    for (var i = 0; i < arr.length; ++i) {
        var remaining = arr.length - i;
        if (arr[i] !== undefined) {
            if (remaining == arr.length) {
                obj['min'] = arr[i];
            }
            else if (remaining === 1) {
                obj['max'] = arr[i];
            }
            else {
                obj[(i*10).toString()] = arr[i];
            }
        }
    }
    return obj;
}
// { 10: "2", 20: "3", 30: "4", min: "1", max: "5" }

How can I sort min to be first in the object and max to be last in the object, convert the key value to a string, and the value to a number: {'min':1, '10%':2, '20%':3, '30%':4, 'max': 5}

My attempt:

function toObject(arr) {
    var obj = {};
    for (var i = 0; i < arr.length; ++i) {
        var remaining = arr.length - i;
        if (arr[i] !== undefined) {
            if (remaining == arr.length) {
                obj["'min'"] = arr[Number(i)];
            }
            else if (remaining === 1) {
                obj["'max'"] = arr[Number(i)];
            }
            else {
                obj["'" + (i*10).toString() + "%'"] = arr[Number(i)];
            }
        }
    }
    return obj;
}
2
  • JSON object's key can't be sorted. You can print them in sorted order but you can't store in the object it self. Commented Sep 24, 2017 at 3:01
  • This may help you - stackoverflow.com/questions/25261002/… Commented Sep 24, 2017 at 3:02

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.