Home > Blockchain >  Check if multiple elements in an array contain the number 3 and then change those values to a specif
Check if multiple elements in an array contain the number 3 and then change those values to a specif

Time:04-03

function beepBoop(input) {
  let arrayBeep = []
  if (Number.isInteger(input) === 0) {
    return true
    } else if (Number.isInteger(input) !== 0) {
    let newNumber = -1
    for (let i = 0; i <= input; i  ) {
      newNumber  ;
      arrayBeep.push(newNumber)

I have the above array and I want to be able to find all elements in that array that contain the number. Once all the numbers that contain have been identified I want to be able to change those numbers to the word Roar. I have already tried doing a for loop but I can't see to get the syntax right.

Output = [0,1,2,Roar,4,5,6,7,8,9,10,11,12,Roar,14,15,16,17,18,19,20,21,22,Roar]

CodePudding user response:

Here's a hint!

When looping over the data...
   if the current element (with index `i`) is equal to the number `input`
       set the `i`-th element to "Roar"

Also, see @SebastianSimon's comment about isInteger.

CodePudding user response:

It doesn't have to be a multi-stage process. You can map over the array and, for each element, coerce it to a string, and check to see if the number is present. If it is return the word, otherwise return the element.

const arr = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23];

// Acceots an array, a number, the replacement word
function change(arr, num, word) {

  // `map` over the array...
  return arr.map(el => {

    // ...create a string from the current element
    // and check to see if the number is present
    // If it is return the word ("Roar")
    if (String(el).includes(num)) return word;

    // Otherwise return the current element
    return el;
  });
}

console.log(change(arr, 3, 'Roar'));

  • Related