Suppose, we have an array of objects like this −
const arr = [ { url: 'www.example.com/hello', id: "22" }, { url: 'www.example.com/hello', id: "22" }, { url: 'www.example.com/hello-how-are-you', id: "23" }, { url: 'www.example.com/i-like-cats', id: "24" }, { url: 'www.example.com/i-like-pie', id: "25" } ];
We are required to write a JavaScript function that takes in one such array of objects. The function should remove such objects from the array that have duplicate id keys. We are required to do this without using any libraries like, underscore.
Let us write the code for this function −
Example
The code for this will be −
const arr = [ { url: 'www.example.com/hello', id: "22" }, { url: 'www.example.com/hello', id: "22" }, { url: 'www.example.com/hello−how−are−you', id: "23" }, { url: 'www.example.com/i−like−cats', id: "24" }, { url: 'www.example.com/i−like−pie', id: "25" } ]; const removeDuplicate = (arr = []) => { const map = {}; for(let i = 0; i < arr.length; ){ const { id } = arr[i]; if(map.hasOwnProperty(id)){ arr.splice(i, 1); }else{ map[id] = true; i++; }; }; }; removeDuplicate(arr); console.log(arr);
Output
And the output in the console will be −
[ { url: 'www.example.com/hello', id: '22' }, { url: 'www.example.com/hello-how-are-you', id: '23' }, { url: 'www.example.com/i-like-cats', id: '24' }, { url: 'www.example.com/i-like-pie', id: '25' } ]