I’m asking little naive question, but I’m seriously I’m not sure how to convert this for loops
const filteredData = csiList.filter(item => {
for (var i = 0, len = this.tableData.length; i < len; i++) {
if (this.tableData[i].csiId == item.appId) {
return false;
}
}
return true;
})
If some one can quickly show how this loops are/is written in more next gen JS ES6/ES7 way, would be of great help
3
Answers
There are a lot of ways to make this more modern code, each step I show here is a based upon the previous:
#1 Use
for...of
loops instead of manually using an index variable (also useconst
since this never changes during the same iteration)#2 Use Destructuring to just get the necessary data (this is an opinion of if it’s better or not, but I’m using more modern features since that’s what you have asked for)
#3 Use
Array.prototype.some
, built for finding if at least one item in a list meets a criteria. Inverted here with!
, since it returnstrue
if at least one items meets the criteria. (Alternatively, useevery
with!==
)#4 Use the implicit return of an arrow function with
{
and}
(on a new line because the width of each line is limited to 80 characters by Prettier‘s opinionated standard)I’m not sure how big your lists are but the solution using .some is O(mn). Meaning you’re cycling through your tableData list multiple times.
Faster would be using a Set(). This solution would be O(n).