Gab
Gab

Reputation: 2276

Looking for a shorter version of my filter function using JS

OK I have this working method to delete files if their id is in the array of Ids:

   deleteFiles(arrayOfIds) {
        let allFiles;
        for (let i = 0; i < arrayOfIds.length; i++) {
            allFiles = this.state.allFiles.filter((file) => {
                return file.id !== arrayOfIds[i];
            });
        }
        this.setState({allFiles});
    }

It works but what is the shorter version using only lodash or Vanilla JS?

Thanks for your help.

Upvotes: 0

Views: 131

Answers (1)

dandavis
dandavis

Reputation: 16726

something like this should work:

  deleteFiles(arrayOfIds) {
        this.setState({ 
           allFiles: this.state.allFiles.filter( 
              file=> arrayOfIds.indexOf(file.id) === -1 
        )});
  }

it uses [].indexOf() to avoid an inner loop, and inlines the other boilerplate to simplify the code.

Upvotes: 1

Related Questions