skip to Main Content

I would want to sort the values in multiple variables and still be able to call on the variable’s names (value1)

      var value1 = 4
      var value2 = 3
      var value3 = 5
      var value4 = 1
      var value5 = 2
      //This are the values that I want to sort//

How would I be able to sort these variables and still be able to call them using their names (value1)

Any help on this situation would be appreciated.

Can you also include an explanation of the code, I would be grateful.

2

Answers


  1. You can sort your variables by putting them into an array an then using .sort() which sorts numbers by value.

    let value1 = 4;
    let value2 = 3;
    let value3 = 5;
    let value4 = 1;
    let value5 = 2;
    //Changed var to let (Better practice)
    
    //Declaring an array. (Separate from value# vairable)
    let values = [value1, value2, value3, value4, value5];
    
    //Sorting right away so nothing is modified in future code.
    values = values.sort();
    
    //Logging results
    console.log("Sorted values: " + values);

    Hope this helps. 🙂

    Edit: On the array I set the value to its own value but sorted. For future instances of code don’t modify original variables.

    Login or Signup to reply.
  2. So this was an interesting one if I understand your question right. But basically, you can do this by lifting your variables up into an object like so:

    var value1 = 4
    var value2 = 3
    var value3 = 5
    var value4 = 1
    var value5 = 2
    
    const data = { value1, value2, value3, value4, value5 };
    

    With that in place, they now have names! So you can use Object to help yourself out:

    const values = Object.values(data).sort();
    Object.keys(data).sort().map((k, idx) => {
        data[k] = values[idx]
    });
    

    This sorts the values of the values and the names of the object, and then matches them up. Which results in:

    {
      value1: 1,
      value2: 2,
      value3: 3,
      value4: 4,
      value5: 5
    }
    

    So now you can call data.value1 to get the value1 out as you indicated in your question and get a value that has been sorted into it.

    This feels like an xy problem question to me though. What are you actually trying to do because sorting an array is a google search away and not an appropriate question for this site.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search