0

The goal here is to is count the number of occurrences in the following array: [2, 3, 7, 9, 7, 3, 2]

For example if the user enters 7, the output should be [2, 4] because 7 occurs at both these indices. What I have so far looks like this

    var arr1 = [2,3,7,9,7,3,2];
    printArray(arr1);
    var indexOfNum = findValueInArray(arr1, num);

    if (indexOfNum === -1) {
    console.log('%d was not found in the array of random integers.', num);
   }
    else {
    console.log('%d was found in the array of random integers at index %d',num, indexOfNum);
}

My results are:

    arr[0] = 2
    arr[1] = 3
    arr[2] = 7
    arr[3] = 9
    arr[4] = 7
    arr[5] = 3
    arr[6] = 2
    7 was found in the array of random integers at index 2

I know I'm close but I'm not sure exactly what I'm overlooking. Thank you guys!

3 Answers3

1

try this,

var arr1 = [2,3,7,9,7,3,2];

function occurance(array,element){
  var counts = [];
    for (i = 0; i < array.length; i++){
      if (array[i] === element) {  
        counts.push(i);
      }
    }
  return counts;
}

occurance(arr1, 2); //returns [0,6]
occurance(arr1, 7); //returns [2,4]
Niranjan N Raju
  • 12,047
  • 4
  • 22
  • 41
0

You can do it like this:

var arr = [2, 3, 7, 9, 7, 3, 2];

function occurrences(x, a) {
  var pos = [];
  a.forEach(function(val, i) {
    if (x === a[i]) {
      pos.push(i);
    }
  });

  return pos;
}

console.log(occurrences(7, arr)); // [2, 4]
console.log(occurrences(5, arr)); // []
console.log(occurrences(2, arr)); // [0, 6]
David Gomez
  • 2,762
  • 2
  • 18
  • 28
0
function findValueInArray(arr, num) {
    var r = [];
    for(i = 0; i < arr.length; i++) (arr[i] == num) ? r.push(i) : '';
    return r;
}

function printArray(num, indexOfNum) {
    console.log('%d was found ... index %s', num, indexOfNum.join(', '));
}

var arr = [2,3,7,9,7,3,2];
var num = 7;
var indexOfNum = findValueInArray(arr, num);
printArray(num, indexOfNum);