skip to Main Content

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


  1. const filteredData = csiList.filter(item => !this.tableData.some(tableDataItem => tableDataItem.csiId === item.appId));
    
    Login or Signup to reply.
  2. 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 use const since this never changes during the same iteration)

    const filteredData = csiList.filter((item) => {
      for (const data of this.tableData) {
        if (data.csiId == item.appId) {
          return false;
        }
      }
      return true;
    });
    

    #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)

    const filteredData = csiList.filter(({ appId }) => {
      for (const { csiId } of this.tableData) {
        if (csiId == appId) {
          return false;
        }
      }
      return true;
    });
    

    #3 Use Array.prototype.some, built for finding if at least one item in a list meets a criteria. Inverted here with !, since it returns true if at least one items meets the criteria. (Alternatively, use every with !==)

    const filteredData = csiList.filter(({ appId }) => {
      return !this.tableData.some(({ csiId }) => csiId === appId);
    });
    

    #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)

    const filteredData = csiList.filter(
      ({ appId }) => !this.tableData.some(({ csiId }) => csiId === appId),
    );
    
    Login or Signup to reply.
  3. 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).

    (() => {
    
    const tableData = [{ csiId: 1 }, { csiId: 2 }, { csiId: 4 }];
    const csiList = [{ appId: 1 }, { appId: 3 }, { appId: 4 }];
    
    const keepers = new Set(tableData.map((data) => data.csiId));
    const filteredData = csiList.filter((obj) => keepers.has(obj.appId));
        
    console.log(filteredData);
    
    })();
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search