- Trending Categories
- 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
How to subtract elements of two arrays and store the result as a positive array in JavaScript?
Suppose, we have two arrays like these −
const arr1 = [1,2,3,4,5,6]; const arr2 = [9,8,7,5,8,3];
We are required to write a JavaScript function that takes in two such arrays and returns an array of absolute difference between the corresponding elements of the array.
Therefore, for these arrays, the output should look like −
const output = [8,6,4,1,3,3];
We will use a for loop and keep pushing the absolute difference iteratively into a new array and finally return the array.
Example
Following is the code −
const arr1 = [1,2,3,4,5,6]; const arr2 = [9,8,7,5,8,3]; const absDifference = (arr1, arr2) => { const res = []; for(let i = 0; i < arr1.length; i++){ const el = Math.abs((arr1[i] || 0) - (arr2[i] || 0)); res[i] = el; }; return res; }; console.log(absDifference(arr1, arr2));
Output
This will produce the following output in console −
[ 8, 6, 4, 1, 3, 3 ]
Advertisements