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

134
Views
Removing values in a range from an array

I want to remove values in a range from an array. For example, removeVals([20, 30, 40, 50, 60, 70], 2, 4) should return the index [20, 30, 70]. How can I solve this problem?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

  1. Create a new array inside the function.
  2. Add the values in the range array[0, removeStartIndex - 1] to the new array.
  3. Add values from range array[removeStopIndex + 1, array.lenght - 1] to the new array.

/**
 * This function removes values from a defined range inside an array.
 * Input → array[]
 * Output → array[0, removeStartIndex - 1] + array[removeStopIndex + 1, array.length - 1]
 * @param {Array<Number>} array
 * @param {Number} removeStartIndex
 * @param {Number} removeStopIndex
 * @returns {Array<Number>}
 */
function removeVals(array, removeStartIndex, removeStopIndex) {
  let resultArray = []
  
  if(array.length != 0 && removeStartIndex < removeStopIndex) {
    if(array.length > removeStartIndex && array.length >= removeStopIndex) {
      for(let i = 0 ; i < removeStartIndex ; ++i) {
        resultArray.push(array[i])
      }

      for(let i = removeStopIndex + 1 ; i < array.length ; ++i) {
        resultArray.push(array[i])
      }
    }
  }
  
  return resultArray;
}

let array= [20, 30, 40, 50, 60, 70]
console.log(removeVals(array, 2, 4))

about 4 years ago · Juan Pablo Isaza Report

0

This can be done in one-liner. If you're unfamiliar with arrow functions this might be a bit confusing but I'll put my solution out there anyway.

var removeVals = (array, start, end) => array.filter((item, index) => index < start || index > end);
console.log(removeVals([20, 30, 40, 50, 60, 70], 2, 4)) // [20, 30, 70]

JavaScript's built-in filter function iterates through an array, and passes each item (and the index of said item optionally) into the function that it's provided. If the return value of that function is true, then the item stays in the array, otherwise it is removed. The function that we pass into the filter function only returns true if the index of the current item in the array is less than the beginning of the range or more that the end of the range, therefore removing items that are in the range.

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!