Using a forEach loop to cycle through a range of numbers, and replace any number that includes the integer of 1 with "Beep"

Viewed 445

I am new to javaScript and struggle a bit with looping and writing functions. I am trying to come up with a function that cycles through my rangeArray where the users inputted number is the end of the array, and each integer that includes 1 is replaced with "Beep" up to that users inputted number. Ex: [ 0, "Beep", 2, 3, 4, 5, 6, 7, 8, 9, "Beep", "Beep", 12 ]. 12 and 2 will be different because later I intend on adding an exception where if a number includes any integer of 2, it supersedes the "Beep" and will replace it with "Boop". Does anyone have any idea how this function would be written? So far I've attempted writing a .includes or even using splice but so far I have only been able to replace the number 1 and nothing else. Help would be much appreciated! Thank you :)

Here is my code so far:

function convertToNumber(input) {
  let parsedInput = parseInt(input);
  console.log(input);
  if (!isNaN(parsedInput)) {
    return parsedInput;
  } else {
    return false;
  }
}
function rangeOfNumbers(start,end) {
  let rangeArray = [];
  for (let i = start; i <= end; i++) {
    rangeArray.push(i + " ");
    
  }
  if (rangeArray); {
    rangeArray.forEach (function (number) {
      rangeArray.splice(1,'1',"Beep");
    }); return rangeArray;
  };
}


console.log(rangeOfNumbers(0,12));
2 Answers

To create a new array, use Array.prototype.map with RegExp.prototype.test to cast integers to string and test for a specific value is contained:

const beepify = arr => arr.map(v => (
  /2/.test(v) ? "Boop" :
  /1/.test(v) ? "Beep" :
v));

console.log(beepify([0,1,2,3,4,5,6,7,8,9,10,11,12]));

Read also about Ternary Operator which is used above in a superceding manner as desired.

You can use Array#map.

function rangeOfNumbers(start,end) {
  let rangeArray = [];
  for (let i = start; i <= end; i++) {
    rangeArray.push(i + "");
  }
  return rangeArray.map(x => x.includes("2") ? "Boop" : x.includes("1") ? "Beep" : x);
}
console.log(rangeOfNumbers(0,12).join());

Array.from can also be used.

function rangeOfNumbers(start,end) {
  return Array.from({length:end-start+1},
   (_,i)=>(i+start+"").includes("1") ? "Beep": i + start);
}
console.log(rangeOfNumbers(0,12).join());

Related