Assume we have the following array of Objects (the real has 71000 elements, but 4 objects are enough to give you an idea):
[
{
source: "France"
target: "Morocco"
timeN: "2008"
valueN: "252.35"
},
{
source: "France"
target: "Morocco"
timeN: "2009"
valueN: "424.12"
},
{
source: "France"
target: "Morocco"
timeN: "2010"
valueN: "152.24"
},
{
source: "France"
target: "Morocco"
timeN: "2011"
valueN: "-342.19"
}
]
How can I efficiently swap source
and target
values on the last object, if valueN
is negative? I would like to just multiply valueN
with -1
or call Math.abs()
and then change also source
to "Morocco"
and target
to "France"
.
Although all answers are great and I have taken the clean one by @Nina Scholz. However, the one from @Emil S. Jørgensen is the most performant one, once tracking the execution time. I don't know why but it seems to be most performant if you do not convert it back to a string
, the valueN
.
var array = [{ source: "France", target: "Morocco", timeN: "2008", valueN: "252.35" }, { source: "France", target: "Morocco", timeN: "2009", valueN: "424.12" }, { source: "France", target: "Morocco", timeN: "2010", valueN: "152.24" }, { source: "France", target: "Morocco", timeN: "2011", valueN: "-342.19" }];
array.forEach(o => {
if (o.valueN < 0) {
[o.source, o.target] = [o.target, o.source];
o.valueN *= -1;
}
});
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments