Home > front end >  Comparing two arrays and remove items in array1 where the index in array2 is undefined
Comparing two arrays and remove items in array1 where the index in array2 is undefined

Time:12-03

Let's say I have these two arrays

steps = [0, 2, 4, 6, 8, 10, 12, 15, 20, 25, 30, 35, 40, 45, 50]

nums = [16.931728, 16.975609, 17.09624, undefined, undefined, undefined..., 5] 

Both arrays are guaranteed to always have the same length.

I want to remove all the undefined values from my nums array, and then remove items at the matching index in my steps array.

Is there a neat way to do this?

I can achieve this by doing nums.filter, and then keep track of the removed indexes in an array.

and then loop through the array of removed indexes backwards to remove the items in the steps array, but this feels wayyy messy. Is there a simply way to approach this?

The end result should be

steps = [0, 2, 4, 50]
nums = [16.931728, 16.975609, 17.09624, 5] 

CodePudding user response:

You could use Array.reduce() to create the required output.

For each item in the steps array, we'll check if the corresponding nums array is undefined, if it is we skip adding to the output arrays.

let steps = [0, 2, 4, 6, 8, 10, 12, 15, 20, 25, 30, 35, 40, 45, 50]
let nums = [16.931728, 16.975609, 17.09624, undefined, undefined, undefined, undefined, undefined, undefined,  undefined, undefined, undefined, undefined, undefined, 5] 

let result = steps.reduce((acc, val, i) => { 
    if (nums[i] !== undefined) {
        acc.nums.push(nums[i]);
        acc.steps.push(val);
    }
    return acc;
}, { steps: [], nums: [] })

console.log('steps:', result.steps);
console.log('nums:', result.nums);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You could take a single loop from the end and remove if necessary.

const
    steps = [0, 2, 4, 6, 8],
    nums = [16.931728, 16.975609, undefined, undefined, 17.09624] 

let i = nums.length;

while (i--) {
    if (nums[i] !== undefined) continue;
    steps.splice(i, 1);
    nums.splice(i, 1);
}

console.log(...steps);
console.log(...nums);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related