3.7 KiB
3.7 KiB
id, title, challengeType, forumTopicId
id | title | challengeType | forumTopicId |
---|---|---|---|
587d7b7b367417b2b2512b15 | Iterate Through All an Array's Items Using For Loops | 1 | 301161 |
Description
every()
, forEach()
, map()
, etc.), however the technique which is most flexible and offers us the greatest amount of control is a simple for
loop.
Consider the following:
function greaterThanTen(arr) {
let newArr = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i] > 10) {
newArr.push(arr[i]);
}
}
return newArr;
}
greaterThanTen([2, 12, 8, 14, 80, 0, 1]);
// returns [12, 14, 80]
Using a for
loop, this function iterates through and accesses each element of the array, and subjects it to a simple test that we have created. In this way, we have easily and programmatically determined which data items are greater than 10
, and returned a new array containing those items.
Instructions
filteredArray
, which takes arr
, a nested array, and elem
as arguments, and returns a new array. elem
represents an element that may or may not be present on one or more of the arrays nested within arr
. Modify the function, using a for
loop, to return a filtered version of the passed array such that any array nested within arr
containing elem
has been removed.
Tests
tests:
- text: <code>filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18)</code> should return <code>[ [10, 8, 3], [14, 6, 23] ]</code>
testString: assert.deepEqual(filteredArray([ [10, 8, 3], [14, 6, 23], [3, 18, 6] ], 18), [[10, 8, 3], [14, 6, 23]]);
- text: <code>filteredArray([ ["trumpets", 2], ["flutes", 4], ["saxophones", 2] ], 2)</code> should return <code>[ ["flutes", 4] ]</code>
testString: assert.deepEqual(filteredArray([ ['trumpets', 2], ['flutes', 4], ['saxophones', 2] ], 2), [['flutes', 4]]);
- text: <code>filteredArray([ ["amy", "beth", "sam"], ["dave", "sean", "peter"] ], "peter")</code> should return <code>[ ["amy", "beth", "sam"] ]</code>
testString: assert.deepEqual(filteredArray([['amy', 'beth', 'sam'], ['dave', 'sean', 'peter']], 'peter'), [['amy', 'beth', 'sam']]);
- text: <code>filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)</code> should return <code>[ ]</code>
testString: assert.deepEqual(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3), []);
- text: The <code>filteredArray</code> function should utilize a <code>for</code> loop
testString: assert.notStrictEqual(filteredArray.toString().search(/for/), -1);
Challenge Seed
function filteredArray(arr, elem) {
let newArr = [];
// Only change code below this line
// Only change code above this line
return newArr;
}
console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));
Solution
function filteredArray(arr, elem) {
let newArr = [];
for (let i = 0; i<arr.length; i++) {
if (arr[i].indexOf(elem) < 0) {
newArr.push(arr[i]);
}
}
return newArr;
}