Manipulating Javascript Array with for-of

bimbowande
2 min readJul 21, 2022

--

1. Filtering an array with for-of

function filterArray( arrayList, callBackFunc){
const output = [];

for(const val of arrayList){
if(callBackFunc(val)){
output.push(val)
}
}
return output}
filterArray(['','Mango','','Apple',''], str => str.length > 0)

2. Mapping an array with for-of

function mapArray(arrayList, callBackFunc){
const output = [];

for(const val of arrayList){
output.push(callBackFunc(val));
}


return output
}mapArray([1,2,3], num => num + num);

3. Filtering and Mapping an array with for-of

function getSeriesTitles(cwSeries, minRating){   const output= [];   for(const series of cwSeries){      if(series.rating >= minRating) result.push(series.title)     }    return output
}
const cwSeries= [ { title: 'Arrow', rating: 8.8 }, { title: 'Flash', rating: 7.9 }, { title: 'Lucifer', rating: 8.1 }, { title: 'Legends of Tomorrow', rating: 8.5 }, { title: 'Super Girl', rating: 7.8 },
];

getSeriesTitles(cwSeries, 8);

4. Finding an item in an Array with for-of

function findInArray(arrayList,callBackFunc){   for(const[index,value] of arrayList.entries()){     if(callBackFunc(value)) return{index,value}     }    return undefined}findInArray(['','a','','bimbo','c','tao'],str=> str.length > 1);

5. Finding the average of the values in an array of objects with for-of

function averageStudentGrade(students){     let sumOfGrades = 0;     for(const student of students){        sumOfGrades += student.grade;        }       return sumOfGrades / students.length;    }const STUDENTS = [
{
id: 'qk4k4yif4a',
grade: 4.0,
},
{
id: 'r6vczv0ds3',
grade: 0.25,
},
{
id: '9s53dn6pbk',
grade: 1,
}
];averageStudentGrade(STUDENTS);

6. Checking a condition with for-of

function everyArrayElement(arrayList,condtion){     for(const elem of arrayList){        if(!condtion(elem)){           return false          }       }         return true;
}
everyArrayElement(['a','','b'], str =>str.length > 1);

Thank you….

--

--

bimbowande

Writer, Designer, Full Stack Developer, Thinker, Reader,.