-2

just a quick question. How can I retrieve elements in an array given that the elements cannot be divided by other elements in an array? for example= arr =[2,3,4,5,6,7,8,9,10,11,12,13,14,15,16] and collection =[2,3,5,7], then the result would be result =[11,13]

I have tried with this code , but it didn't work

for(var i=0; i<arr.length;i++){
    for (var j=0; j<collection.length; j++){
      if (arr[i]/collection[j] === 0){
        arr.splice(i,1);
      }
    }
  }
Owennn
  • 85
  • 5

2 Answers2

2

Something like this

1) using filter and forEach:

var arr =[2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];

var collection =[2,3,5,7];


function notDivided(arr1, arr2) {

    return arr1.filter( function(item) {
        var can_be_divided = false;
        arr2.forEach( function(item_to_divide) {
            if (item % item_to_divide === 0) can_be_divided = true;
        });
        return !can_be_divided;
    });

}

var new_array = notDivided(arr,collection);

console.log(new_array);

2) using filter and some (@torazaburo's suggestion)

function notDivided(arr1, arr2) {

    return arr1.filter( function(item) {
        return !arr2.some( function(item_to_divide) {
            return (item % item_to_divide === 0);
        });
    });

}

Or, yet, using arrow functions:

notDivided = (arr1, arr2) => arr1.filter( (item) => !arr2.some( (item_to_divide) => item % item_to_divide === 0 ) );
mrlew
  • 7,078
  • 3
  • 25
  • 28
  • Why are you using `forEach` with outside variables instead of just using `some`, which would make it as simple as `return arr2.some(item_to_divide => !(item % item_to_divide))`? –  Jun 17 '16 at 04:05
0

declare new array to collect results

use % symbol to check

example 4 % 2 = 0

this mean 4 can be divided by 2 because result is 0 so you can make

if (!(arr[i]%collection[j] === 0)){
    newarr.push(arr[i])
  }

edited if you wanna example without think here return what you post too

var arr =[2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];
var collection =[2,3,5,7];
var newarr=[];
var addtonew = 0;

for(var i=0; i < arr.length; i++){
  addtonew = -1;
  for (var j=0; j<collection.length; j++){
    if (arr[i]%collection[j] === 0)
     {
      addtonew = -1;
      break;
     }
    addtonew = arr[i];
  }
 if (addtonew > -1 )
    newarr.push(addtonew);
 }

 #[11, 13]
George Poliovei
  • 1,009
  • 10
  • 12