FreeCodeCampBeta -Iterate Through All an Array's Items Using For Loops - Question

FreeCodeCampBeta -Iterate Through All an Array's Items Using For Loops - Question
0.0 0

#1

Hello, is there a better way to do this challenge than mine:
Link: https://beta.freecodecamp.org/en/challenges/basic-data-structures/iterate-through-all-an-arrays-items-using-for-loops


function filteredArray(arr, elem) {
	let newArr = []; 
	let arrL = arr.length; //4
		
	for( let k = 0; k < arrL; k++ ) {
		for( let i = 0; i < arr[k].length; i++ ) {
			if( arr[k][i] == elem ) {
				arr[k].splice(0, arr[k].length);
			}
		}	
	}
	
	for( let d = 0; d < arr.length; d++) {
		if( arr[d].length > 0) {
			newArr.push( arr[d] );
		}
	}
	return newArr;

};

console.log(filteredArray([[10, 8, 3], [14, 6, 23], [3, 18, 6]], 18));

And by better, i’m sure this part can be a lot better:

	for( let d = 0; d < arr.length; d++) {
		if( arr[d].length > 0) {
			newArr.push( arr[d] );
		}
	}
	return newArr;

I’m looking for some thing to delete empty Array in Array.


#2

If you don’t mind modifying the original array, you could modify your solution as:

function filteredArray(arr, elem) {
	let arrL = arr.length; //4
		
	for( let k = 0; k < arrL; k++ ) {
		for( let i = 0; i < arr[k].length; i++ ) {
			if( arr[k][i] == elem ) {
				arr.splice(k, 1);
				break;
			}
		}	
	}
	return arr;
}

If you do not want to modify the original array:

function filteredArray(arr, elem) {
	let newArr = []; 
	let arrL = arr.length; //4
		
	for( let k = 0; k < arrL; k++ ) {
		for( var i = 0; i < arr[k].length; i++ ) { // notice the change from let to var
			if( arr[k][i] === elem ) 
				break;
		}	
		if (i === arr[k].length) // will add subarray if we iterated through without break
		  newArr.push(arr[k]);
	}
	return newArr;
}

#3

A post was split to a new topic: Can someone tell me why my code doesn’t work just on filteredArray


#5

Hi ;
This is my code . It is a shorter way with indexOf()

function filteredArray(arr, elem) {
let newArr = [];
// change code below this line
for( var i = 0 ; i<arr.length ; i++){
if (arr[i].indexOf(elem) === -1){
newArr.push(arr[i]);
}
}
// change code above this line
return newArr;
}

// change code here to test different cases:
console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));