Home > front end >  I cannot find even and odd numbers in an array javascript
I cannot find even and odd numbers in an array javascript

Time:12-31

https://i.stack.imgur.com/Nv1Bo.png

I know how to find an even or odd number but I can't seem to find any results for finding odd and even numbers in an array. I want to write even numbers in a paragraph in HTML and odd numbers in another paragraph.

let numbers = [1,2,3,4,5,6,7,8,9,10]

let e;
let no = numbers.forEach(sort());

function sort() {
  if(numbers[e] % 2 === 0) {
    console.log(`${numbers[e]} is even`);
    // document.querySelector("#even").innerHTML = numbers[e];
  } else {
     console.log(`${numbers[e]} is odd`);
     // document.querySelector("#odd").innerHTML = numbers[e];
  }
}

CodePudding user response:

Pass sort to forEach, don't call that

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

function sort(e) {
  const type = e % 2 === 0 ? "even" : "odd";
  console.log(`${e} is ${type}`);
}
const no = numbers.forEach(sort);

CodePudding user response:

Using a for loop and an if statement.

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

function sort() {
  for (let e = 0; e < numbers.length; e  ) {
    if (numbers[e] % 2 === 0) {
      console.log(`${numbers[e]} is even`);
      // document.querySelector("#even").innerHTML = numbers[e];
    } else {
      console.log(`${numbers[e]} is odd`);
      // document.querySelector("#odd").innerHTML = numbers[e];
    }
  }
}

sort()

CodePudding user response:

You can run it like below so if you wanna check it using the i which is key then remove comment part of if otherwise continue with the same.

let numbers = [1,2,3,4,5,6,7,8,9,10]

numbers.forEach((val, i) => sort(i, val));

function sort(i, val) {
  //if(numbers[i] % 2 === 0) {
  if(val % 2 === 0) {
    //console.log(`${numbers[i]} is even`);
    console.log(`${val} is even`);
  } else {
     //console.log(`${numbers[i]} is odd`);
     console.log(`${val} is odd`);
  }
}

CodePudding user response:

const numbers = [1,2,3,4,5,6,7,8,9,10]

// Cache your elements so you're not
// picking them up in each iteration
const even = document.querySelector("#even");
const odd = document.querySelector("#odd");

// forEach doesn't return anything so
// there's no point assigning it to a variable
// Additionally you should be assigning the reference
// of `sort` as the callback, not the result of
// calling the function
numbers.forEach(sort);

// Make sure you pass in your element to the function
function sort(el) {
  
  // Now just check that element
  if (el % 2 === 0) {
    
    // And I'd recommend using textContent as concatentation
    // with innerHTML reparses the HTML
    // each time which can be a performance hit
    // See link below
    even.textContent  = el;
  } else {
    odd.textContent  = el;
  }
}
<div id="even"></div>
<div id="odd"></div>

Why is "element.innerHTML =" bad code?

CodePudding user response:

You should do something like this

let numbers = [1,2,3,4,5,6,7,8,9];
// Your sort function
function sort(n) {
  if((n % 2) === 0)
    document.querySelector('#even').innerHTML  = n   ", ";
  else
    document.querySelector('#odd').innerHTML  = n   ", ";
}
// Append numbers to respective element
numbers.forEach(sort);
Even: <p id="even"></p>
Odd: <p id="odd"></p>

CodePudding user response:

I can see a couple of problems related to the code. I put comments to your code, so you can check why it does not work.

let numbers = [1,2,3,4,5,6,7,8,9,10]

// The initial value for e is not defined so first read from the
// array will look like "numbers[undefined]"
let e;

// The "sort" is called before it's declared, so this might cause
// problems. 
// Also passing callback to the forEach function should look like this
// numbers.forEach(sort). When calling forEach(sort()) you're trying
// to pass a result of the sort() function to forEach which will be 
// undefined.
let no = numbers.forEach(sort());

function sort() {
  // The "e" variable is not initialized and not incremented anywhere
  // so this will not work at all. 
  if(numbers[e] % 2 === 0) {
    console.log(`${numbers[e]} is even`);
    // This piece overwrites content of the HTML tag each time
    // it's called. You need to append to the content.
    
    // document.querySelector("#even").innerHTML = numbers[e];
  } else {
     console.log(`${numbers[e]} is odd`);
    
     // This is affected by the same issue as writing to the 
     // #even tag.

     // document.querySelector("#odd").innerHTML = numbers[e];
  }
}

Working solution for your problem might look like this

HTML

<div id="even"> Even numbers: </div>
<div id="odd"> Odd numbers: </div>

and JavaScript

let numbers = [1, 2, 3, 4, 5 ,6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

function sort(item) {
    // Here you can check if number is even or odd
    // and decide which HTML element should be updated 
    // in just a single line. 
    let tagId = item % 2 === 0 ? "even" : "odd";

    // And here you just updated HTML tag with extra content
    // by appending next numbers separated by a space. 
    document.getElementById(tagId).insertAdjacentHTML('beforeend', item   " ");
}

numbers.forEach(sort);

CodePudding user response:

Details commented in example.

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const parity = array => {
  // Make an array of <p>
  const p = [...document.querySelectorAll('p')];
  /*
  Iterate thru given array
  parity check is 0 or 1
  p[0] first <p>
  p[1] second <p>
  */
  array.forEach((num, idx) => {
    let par = num % 2 === 1 || num === 1 ? 1 : 0; 
    p[par].insertAdjacentText('beforeEnd',num ' ');
  });
};

parity(numbers);
<p></p>
<p></p>

  • Related