Skip to content

Instantly share code, notes, and snippets.

@misterbailey
Created May 7, 2018 22:04
Show Gist options
  • Save misterbailey/3f52ad37309afb9ed39bffef4612da70 to your computer and use it in GitHub Desktop.
Save misterbailey/3f52ad37309afb9ed39bffef4612da70 to your computer and use it in GitHub Desktop.
Array Recursion Task
// Task: Write a function that recursively loops through a multidimensional array and counts the instances of an item
// Le data
var arr = [
'apples',
['apples', 'oranges,', 'bananas', ['apples',]]
];
// A quick and dirty nested loop.
// Will only work if nesting is one level deep
function countItems1 (arr, item) {
var itemCount = 0;
for (var i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
for (var k = 0; k < arr[i].length; k++) {
console.log(arr[i][k]);
if (arr[i][k] === item ) {
itemCount++;
}
}
} else if (arr[i] === item ) {
itemCount++;
}
}
return itemCount;
};
// Proper recursion.
// Will work with infinite levels of nesting
function countItems2(arr, item, itemCount) {
itemCount = 0
for (var i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
var itemCount2 = countItems2(arr[i], item);
itemCount = itemCount + itemCount2;
} else if (arr[i] === item ) {
itemCount++;
}
}
return itemCount;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment