rthames62
rthames62

Reputation: 155

Javascript loop an array to find numbers divisible by 3

I am needing to find the correct way to have javascript loop through an array, find all numbers that are divisible by 3, and push those numbers into a new array.

Here is what I have so far..

var array = [],
    threes = [];

function loveTheThrees(array) {
    for (i = 0, len = array.length; i < len; i++) {
    threes = array.push(i % 3);
  }
  return threes;
}

So if we pass through an array of [1, 2, 3, 4, 5, 6] through the function, it would push out the numbers 3 and 6 into the "threes" array. Hopefully this makes sense.

Upvotes: 1

Views: 12940

Answers (8)

Kim
Kim

Reputation: 55

var array = [],
three = [];
 
function loveTheThrees(array) {
    for (i = 0, len = array.length; i < len; i++) {
        if(array[i] % 3 == 0){
            three.push(array[i]);
        }
    }
    return three;
}

Upvotes: 1

JulienRioux
JulienRioux

Reputation: 3092

In ES6:

const arr = [1, 33, 54, 30, 11, 203, 323, 100, 9];

// This single line function allow you to do it:
const isDivisibleBy3 = arr => arr.filter(val => val % 3 == 0);


console.log(isDivisibleBy3(arr));
// The console output is [ 33, 54, 30, 9 ]

Upvotes: 0

Rohit Shedage
Rohit Shedage

Reputation: 25850

console.log([1, 2, 3, 4, 5, 6, 7].filter(function(a){return a%3===0;}));

Array.filter() iterates over array and move current object to another array if callback returns true. In this case I have written a callback which returns true if it is divisible by three so only those items will be added to different array

Upvotes: 1

MASTERKARR
MASTERKARR

Reputation: 1

var originalArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
function loveTheThrees(array1) {
  var threes = [];
  for (var i = 0; i < array1.length; i++) {
    if (array1[i] % 3 === 0) {
      threes.push(array1[i]);
    }
  }
  return threes;
}
loveTheThrees(originalArray);

Upvotes: 0

Rajshekar Reddy
Rajshekar Reddy

Reputation: 18987

Check if the number is divisible by 3 if so then add it to array. Try this

function loveTheThrees(array) {
    for (i = 0, len = array.length; i < len; i++) {
      if(array[i] % 3 == 0){
        three.push(array[I]);
     }
  }

Upvotes: 0

Shishir Arora
Shishir Arora

Reputation: 5923

loveTheThrees=(arr)=>arr.filter(el=>Boolean(parseFloat(el)) && isFinite(el) && !Boolean(el%3))

es6 version + skipping non numbers

loveTheThrees([null,undefined,'haha',100,3,6])

Result: [3,6]

Upvotes: 0

user3839756
user3839756

Reputation: 813

Using Filter like suggested by Nina is defiantly the better way to do this. However Im assuming you are a beginner and may not understand callbacks yet, In this case this function will work:

function loveTheThrees(collection){
        var newArray = []
        for (var i =0; i< collection.length;i++){
            if (myArray[i] % 3 === 0){
                newArray.push(collection[i])
            }
        }
        return newArray;
    }

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386560

You can use Array#filter for this task.

filter() calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a true value or a value that coerces to true. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. Array elements which do not pass the callback test are simply skipped, and are not included in the new array.

function loveTheThrees(array) {
    return array.filter(function (a) {
        return !(a % 3);
    });
}
document.write('<pre>' + JSON.stringify(loveTheThrees([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), 0, 4) + '</pre>');

Upvotes: 6

Related Questions