Find distinct elements - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of literals, such that some array elements are repeated. We are required to return an array that contains that appear only once (not repeated).

For example: If the array is:>

const arr = [9, 5, 6, 8, 7, 7, 1, 1, 1, 1, 1, 9, 8];

Then the output should be −

const output = [5, 6];

Example

Following is the code −

const arr = [9, 5, 6, 8, 7, 7, 1, 1, 1, 1, 1, 9, 8];
const findDistinct = arr => {
   const res = [];
   for(let i = 0; i < arr.length; i++){
      if(arr.indexOf(arr[i]) !== arr.lastIndexOf(arr[i])){
         continue;
      };
      res.push(arr[i]);
   };
   return res;
};
console.log(findDistinct(arr));

Output

Following is the output in the console −

[5, 6]
raja
Updated on 18-Sep-2020 09:27:48

Advertisements