Reputation: 11
Array given values are in ascendent order!
I want to get a arithmetic sequence with difference of 1 and the starting value should be 0.
Presumably the code provides a good solution in all cases. I think that this is too complicated solution, there must be an easier one. What could it be?
let arr = [{x: "a",num:4},{x: "f",num:5},{x: "k",num:7},{x: "d",num:9}];
let firstVal = arr[0].num;
let j = 0;
while(j != firstVal) {
arr.splice(j,0,{x: "temp",num:j});
j++;
}
let i = 0;
while(arr[arr.length - 1].num != i+1) {
if(arr[i].num + 1 != arr[i+1].num) {
arr.splice(i+1,0,{x: "temp",num:i+arr[0].num+1});
}
i++;
}
Output:
0: {x: 'temp', num: 0}
1: {x: 'temp', num: 1}
2: {x: 'temp', num: 2}
3: {x: 'temp', num: 3}
4: {x: 'a', num: 4}
5: {x: 'f', num: 5}
6: {x: 'temp', num: 6}
7: {x: 'k', num: 7}
8: {x: 'temp', num: 8}
9: {x: 'd', num: 9}
Upvotes: 1
Views: 37
Reputation: 561
let arr = [{x: "a",num:4},{x: "f",num:5},{x: "k",num:7},{x: "d",num:9}];
let num = 0;
while (arr.length !== 0) {
let found = arr.findIndex(item => item.num === num);
if (found !== -1) {
console.log(arr[found]);
arr.splice(found,1);
} else {
console.log({x: "temp", num: num});
}
num++;
}
Upvotes: 1