arraysangulartypescriptrxjs

Most efficient way to create an array based on other arrays


I have an array with varying number of objects like so:

const arrayA = [
  {name: n, value: v}
  {name: n, value: v}
  ...
  {name: n, value: v}
]

I have another array with n number of numbers:

const arrayB = [1, 13, 28]

Length of arrayB is less or equal than of arrayA but never higher.

Now I need to create another array - arrayC: Array<boolean> = []. The length of arrayC should be equal to length of arrayA

arrayA.length == arrayC.length

with all false boolean values apart from those with index of every value from arrayB

I could probably achieve this with bunch of forEach and/or for loops but what I want to know is what would be the most efficient and not resource consuming way to get it.


Solution

  • Create an initial all-false array by making an array with the right length and setting all its elements to the same value:

    const arrayC = Array(arrayA.length).fill(false);
    

    Then set the elements by index:

    for (const i of arrayB) {
        arrayC[i] = true;
    }