Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

173
Views
Comparing two arrays and remove items in array1 where the index in array2 is undefined

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] 
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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; }

about 4 years ago · Juan Pablo Isaza Report

0

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);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!