We are required to write a JavaScript function that takes in an array of literals. The function should prepare a new array of all those elements from the original array that are not unique (duplicate elements.)
For example −
If the input array is −
const arr = [3, 6, 7, 5, 3];
Then the output should be −
const output = [3];
Example
The code for this will be −
const arr = [3, 6, 7, 5, 3];
const makeDuplicatesArray = (arr = []) => {
const res = [];
for(let i = 0; i < arr.length; i++){
if(i === arr.lastIndexOf(arr[i])){
continue;
};
res.push(arr[i])
};
return res;
};
console.log(makeDuplicatesArray(arr));Output
And the output in the console will be −
[3]