<script> var arr = ["apple", "mango", "apple", "orange", "mango", "mango"]; function removeDuplicates(arr) { return arr.filter((item, index) => arr.indexOf(item) === index); } console.log(removeDuplicates(arr)); </script>
Is the filter method returning the whole array or each item one by one?
Here I removed duplicates in Function using filter method. My question is I know filter method creates new array but where does it store that array?
Advertisement
Answer
The filter method returns a whole new array once it’s completed. Primitive values (as you’ve got here) are cloned, but the filter method won’t deep-clone. So if you’re filtering an array of objects, for example, you’ll still get a new array, but with references to the same objects from the original array.
As far as where it’s stored, it wouldn’t be accessible unless you assign it to a variable.
const yourArray = [ "apple", "mango", "apple", "orange", "mango", "mango" ]; const newArray = removeDuplicates(yourArray); console.log(newArray); function removeDuplicates(arr) { return arr.filter((item, index) => arr.indexOf(item) === index); } // console shows ["apple","mango","orange"]