1

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.

2
  • function loveTheThrees(a) { a.filter(function(a, i) {return a % 3 == 0}) } Commented Mar 30, 2016 at 18:43
  • You are pushing i%3 into array and then reassigning all of array to three. Suggestions are to use more meaningful names rather than array, learn about array and assignment operations in js Commented Mar 30, 2016 at 18:44

8 Answers 8

6

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>');

Sign up to request clarification or add additional context in comments.

1 Comment

Damn you won by quicker fingers.
1

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

1 Comment

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
1
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;
}

Comments

0

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;
    }

Comments

0

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]

Comments

0

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]);
     }
  }

1 Comment

If anybody can edit this code block it will be helpful. I am on mobile app and no feature to add code block.. Thanks
0
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);

1 Comment

Welcome to Stack Overflow! While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.
0

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 ]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.