Home > other >  Replace a list of undefined values with a list of elements placing them at a specific index position
Replace a list of undefined values with a list of elements placing them at a specific index position

Time:09-09

I have an array of numbers which i want to use as an index position in the splice method, an array with 10 undefined values that serve as empty slots (index positions), and a years array.

const positionsOfYears = [2, 5, 8];
const emptyArray [undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined,];
const years = [1992, 1999, 2000];

My desired output is this

emptyArray = [undefined, undefined, 1992, undefined, undefined, 1999, undefined, undefined, 2000, undefined]

Thank you

CodePudding user response:

You need to loop through positionsOfYears array and each item will be the index in emptyArray, let's call it emptyArrayIndex, then set emptyArray[emptyArrayIndex] = years[index]

const positionsOfYears = [2, 5, 8];
const emptyArray = [undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined,];
const years = [1992, 1999, 2000];

positionsOfYears.forEach((emptyArrayIndex, index) => emptyArray[emptyArrayIndex] = years[index])

console.log(emptyArray)

CodePudding user response:

const resultArr = [];
const positions = [2, 5, 8];
const numbers = [12, 13, 14];
let counter = 0;
for (let i = 0; i < 10; i  = 1) {
  if (positions.includes(i)) {
    resultArr[i] = positions[positions.indexOf(i)];
  } else {
    resultArr[i] = undefined;
  }
};
console.log(resultArr);
I don't know is this best solution :}

  • Related