- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Subtracting array in JavaScript Delete all those elements from the first array that are also included in the second array
Suppose, we have two arrays of literals like this −
const arr1 = ['uno', 'dos', 'tres', 'cuatro']; const arr2 = ['dos', 'cuatro'];
We are required to write a JavaScript function that takes in two such arrays and delete all those elements from the first array that are also included in the second array.
Therefore, for these arrays, the output should look like this −
const output = ['uno', 'tres'];
Example
const arr1 = ['uno', 'dos', 'tres', 'cuatro']; const arr2 = ['dos', 'cuatro']; const findSubtraction = (arr1 = [], arr2 = []) => { let filtered = []; filtered = arr1.filter(el => { if(arr2.indexOf(el) === -1){ return true; }; }); return filtered; }; console.log(findSubtraction(arr1, arr2));
Output
And the output in the console will be −
[ 'uno', 'tres' ]
Advertisements
To Continue Learning Please Login
Login with Google