let's say we have an array like this:
[
{l:A,n:1},
{l:B,n:2},
{l:C,n:3},
{l:D,n:4},
{l:E,n:5}
]
I want to change order of 2 values: C become 5 and D become 2.
If i use a cycle like this to swap values...
const arr = [
{l:A,n:1},
{l:B,n:2},
{l:C,n:3},
{l:D,n:4},
{l:E,n:5}
]
const changes = [
{l:C,n:5},
{l:D,n:2}
]
changes.forEach(change => {
const changedI = arr.findIndex( x => x.l == change.l)
const swappedI = arr.findIndex( x => x.n == change.n)
const changedN = arr[changedI].n
arr[changedI].n = change.n
arr[swappedI].n = changedN
})
[
{l:A,n:1},
{l:B,n:4},
{l:C,n:5},
{l:D,n:2},
{l:E,n:3}
]
But i need that the result array is ordered (only) for non changed elements, like this:
[
{l:A,n:1},
{l:B,n:3},
{l:C,n:5},
{l:D,n:2},
{l:E,n:4}
]
therefore only the changed elements remain fixed, while the elements not expressly changed are rearranged from the smallest to the largest.
I was thinking of doing it with two loops where on the first i swap the slots, and on the second i rearrange only the unchanged elements, but I think there is a faster way, perhaps with a recursion?
You could take a single loop approach and store open object who need to get a new number and another for missing numbers.
With
change = [['C', 5], ['D', 2]]
You get
data = [ v
{ l: 'A', n: 1 }, // 1
{ l: 'B', n: 2 }, // 3
{ l: 'C', n: 3 }, // <- 5 5
{ l: 'D', n: 4 }, // <- 2 2
{ l: 'E', n: 5 } // 4
]
With
change = [['C', 1]]
You get
data = [ v
{ l: 'A', n: 1 }, // 2
{ l: 'B', n: 2 }, // 3
{ l: 'C', n: 3 }, // <- 1 1
{ l: 'D', n: 4 }, // 4
{ l: 'E', n: 5 } // 5
]
const
data = [
{ l: 'A', n: 1 }, // 2
{ l: 'B', n: 2 }, // 3
{ l: 'C', n: 3 }, // <- 1 1
{ l: 'D', n: 4 }, // 4
{ l: 'E', n: 5 } // 5
],
//change = [['C', 5], ['D', 2]],
change = [['C', 1]],
open = [],
missing= [];
data.forEach(o => {
if (change.some(([, v]) => v === o.n)) {
if (missing.length) o.n = missing.shift();
else open.push(o);
return;
}
const pair = change.find(([k]) => k === o.l);
if (pair) {
if (open.length) open.shift().n = o.n;
else missing.push(o.n);
o.n = pair[1];
return;
}
open.push(o);
open.shift().n = o.n;
});
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments