Reputation: 732
I have an array of objects called thresholds :
thresholds: [{
dType: "threshold",
from: 0,
to: 30,
color: "#D91427"
},
{
dType: "threshold",
from: 30,
to: 70,
color: "#F2910A"
},
{
dType: "threshold",
from: 70,
to: 120,
color: "#219131"
}
]
How do I set the color
property of each object in reverse?
For example , something like this ,
thresholds: [{
dType: "threshold",
from: 0,
to: 30,
color: "#219131"
},
{
dType: "threshold",
from: 30,
to: 70,
color: "#F2910A"
},
{
dType: "threshold",
from: 70,
to: 120,
color: "#D91427"
}
]
Upvotes: 1
Views: 58
Reputation: 3066
It is simple Ariff, just loop through the thresholds
array. Calculate the total length of the array, and loop through the half of it, swapping the color
values of objects inside the thresholds[]
which correspond to each other on opposite ends, for example, 1st element -- last element, 2nd element -- 2nd element from last, and so on...
Here is the code snippet. I hope it helps.
var thresh_len = thresholds.length-1;
for(var i = 0; i < (thresh_len/2); i++) {
var temp = thresholds[i].color;
thresholds[i].color = thresholds[(thresh_len - i)].color;
thresholds[(thresh_len - i)].color = temp;
}
Upvotes: 1
Reputation: 4553
reverse()
property of Array
to reverse the array, so that the reference is also reversedgetThresholds(colors) {
return [{
dType: "threshold",
from: 0,
to: 30,
color: colors[0]
},
{
dType: "threshold",
from: 30,
to: 70,
color: colors[1]
},
{
dType: "threshold",
from: 70,
to: 120,
color: colors[2]
}]
}
const colors = ["#219131", "#F2910A", "#D91427"]
thresholds : getThresholds(colors)
thresholds : getThresholds(colors.reverse())
Upvotes: 0
Reputation: 15247
I'd loop from 0 to (len - 1) / 2
and swap each color
let thresholds = [{
dType: "threshold",
from: 0,
to: 30,
color: "#D91427"
},
{
dType: "threshold",
from: 30,
to: 70,
color: "#F2910A"
},
{
dType: "threshold",
from: 70,
to: 120,
color: "#219131"
}
];
function swap(obj, i, len)
{
let temp = obj[i].color;
obj[i].color = obj[len - 1 - i].color;
obj[len - 1 - i].color = temp;
}
let arrayLen = thresholds.length;
for (let i = 0; i <= Math.floor((arrayLen - 1) / 2); ++i)
{
swap(thresholds, i, arrayLen);
}
console.log(thresholds);
Upvotes: 0