I have the following arrangement:
let arreglo=[{'class':1,'var':1, 'valor':50},
{'class':3,'var':2, 'valor':150},
{'class':1,'var':2, 'valor':200},
{'class':1,'var':1, 'valor':60},
{'class':3,'var':2, 'valor':520},
{'class':1,'var':2, 'valor':250}];
I want to discriminate by ordering according to the 'class' attribute
[{'class':1,'var':1, 'valor':50},
{'class':1,'var':2, 'valor':200},
{'class':1,'var':1, 'valor':50},
{'class':1,'var':2, 'valor':250}]
[{'class':3,'var':2, 'valor':150},
{'class':3,'var':2, 'valor':520}];
then discriminate according to the 'var' attribute to get
[{'class':1,'var':1, 'valor':50},
{'class':1,'var':1, 'valor':50},
{'class':1,'var':2, 'valor':200},
{'class':1,'var':2, 'valor':250}]
[{'class':3,'var':2, 'valor':150},
{'class':3,'var':2, 'valor':520}];
my code is the following but what I do is discriminate and then I would have to join the arrays, I want a more efficient way.
let arreglo = [{'class': 1,'var': 1,'valor': 50},
{'class': 3, 'var': 2,'valor': 150 },
{'class': 1, 'var': 2,'valor': 200 },
{'class': 1, 'var': 1,'valor': 60 },
{'class': 3, 'var': 2,'valor': 520 },
{'class': 1, 'var': 2,'valor': 250 }
];
function filtrarSegunVariable(arreglo, variable, condicion) {
return arreglo.filter(function(x) {
if (x[variable] === condicion) {
return x;
}
})
}
let class1 = filtrarSegunVariable(arreglo, 'class', 1);
let class3 = filtrarSegunVariable(arreglo, 'class', 3);
console.log(filtrarSegunVariable(class1, 'var', 1));
console.log(filtrarSegunVariable(class1, 'var', 2));
console.log(filtrarSegunVariable(class3, 'var', 1));
console.log(filtrarSegunVariable(class3, 'var', 2));
note: values 1, 2, 3 must be strings
To order handling of arrays there are many functions that can be used without having to resort to
for
orwhile
in this case you can use theArray.prototype.sort
.The way this function is used is as follows:
1) I declare my array:
2) I sort it: myArray.sort((a,b)=>{ return ab; });
the result would be: [1,2,3,4,5,7] What goes inside the sort is a callback that indicates how the array should be ordered, for more information see this link
So to order your array you just have to adapt the callback to your needs:
Your arrangement is already ordered.
You can pass the method
sort
a comparison function. So what you could do is pass a function that first sorts by comparing one value (class) and if they're equal, sorts by comparing by a second value (var) and if they're equal, sorts by comparing by a third value (value).Something like this:
Here you can see it working:
And here you can see how it also works if the values were strings: