0
votes

I'm trying to build an object for my noUiSlider range property dynamically in JavaScript. Creating a step based range slider requires a min and a max value, and all the values in between should be a percentage of the total value of items. The following example would create a range slider with 3 steps, 1, 5, and 10.

range: {
    'min': 1,
    '50%': 5,
    'max': 10
}

My data comes in as follows:

[
  {width: "1"},
  {width: "1.5"},
  {width: "2"},
  {width: "3"},
  {width: "4"}
]

This array could be any number of widths. With my incoming data, I need to format it into an object that my range slider accepts. Something similar to this:

{                       {
    'min': 1,               'min': 1,
    '25%': 1.5,             '16.66%': 1.5,
    '50%': 2,      OR       '33.32%': 2,
    '75%': 3,               '49.97%': 3,
    'max': 4                '66.66%': 4,
}                           '83.32%': 5,
                            'max': 6
                        }

The key value must contain a min value as the first item and a max value as the last item. The rest of the keys must be calculated as a percentage based on the number of items in the width array, and the values would be width value of the array.

I've tried creating the obj with the following code but don't know how to set the first and last key values to min and max

function toObject(arr) {
    var obj = {};
    for (var i = 0; i < arr.length; ++i)
        if (arr[i] !== undefined) obj[i*10] = arr[i];
    return obj;
}
1
All you have shown is the goal ... but not any attempts to solve this yourself or really any specific code related problem. This isn't a free code writing service, the objective here is to help you fix your code - charlietfl
Sorry, I've updated my question. - Romes

1 Answers

1
votes

What about checking the remaining elements as you iterate:

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].width;
            }
            else if (remaining === 1) {
                obj['max'] = arr[i].width;
            }
            else {
                obj[(i*10).toString()] = arr[i].width;
            }
        }
    }
    return obj;
}

A test from the console:

>var a = [
  {width: "1"},
  {width: "1.5"},
  {width: "2"},
  {width: "3"},
  {width: "4"}
];
>
>toObject(a)
{10: "1.5", 20: "2", 30: "3", min: "1", max: "4"}