Sort multiple object arrays by value

0

People have the following situation:

var input1 = {preco:valor1.toFixed(3), tipo:name1};
var input2 = {preco:valor2.toFixed(3), tipo:name2};
var input3 = {preco:valor3.toFixed(3), tipo:name3};
var input4 = {preco:valor4.toFixed(3), tipo:name4};

and I would like to display the values of these 4 arrays in ascending order of 'price' as follows:

Lowest price: type: price Second lowest value: type2: preco2 (...)

How can I sort the 4 arrays according to the value of one of the objects in each of them?

EDIT to better exemplify:

var valor1 = 50;
var name1  = "nome1";
var valor2 = 20;
var name2  = "nome2";
var valor3 = 60;
var name3  = "nome3";
var valor4 = 10;
var name4  = "nome4";

var input1 = {preco:valor1.toFixed(3), tipo:name1};
var input2 = {preco:valor2.toFixed(3), tipo:name2};
var input3 = {preco:valor3.toFixed(3), tipo:name3};
var input4 = {preco:valor4.toFixed(3), tipo:name4};

and after sorting, in that case, you should print

Lowest Value: name4 - 10

Second Lowest Value: name2 - 20

Third Lower Value: name1 - 50

Room Minor Value: name3 - 60

    
asked by anonymous 02.03.2016 / 15:57

1 answer

1

To sort by value by keeping the relationship with the name, you must mount an array with your tuples, then perform a sort ...

But as we are sorting by value, we can not make a toFixed , as this will turn the value into a string ...

var valor1 = 2002.46;
var valor2 = 1001.23;
var valor3 = 4004.92;
var valor4 = 3003.69;

var name1 = "name1";
var name2 = "name2";
var name3 = "name3";
var name4 = "name4";

var intl = new Intl.NumberFormat("pt-BR", { minimumFractionDigits: 3 });
var inputs = [
    { preco: valor1, tipo: name1 },
    { preco: valor2, tipo: name2 },
    { preco: valor3, tipo: name3 },
    { preco: valor4, tipo: name4 }
];

inputs = inputs.sort(function (inputA, inputB) {
  return inputA.preco > inputB.preco;
});
inputs.forEach(function (input) {
  input.preco = intl.format(input.preco);
});

var input1 = inputs[0];
var input2 = inputs[1];
var input3 = inputs[2];
var input4 = inputs[3];

console.log(input1, input2, input3, input4);

The output of the above code will be:

input1: {preco: "1.001,230", tipo: "name2"} 
input2: {preco: "2.002,460", tipo: "name1"} 
input3: {preco: "3.003,690", tipo: "name4"} 
input4: {preco: "4.004,920", tipo: "name3"}
    
02.03.2016 / 17:14