1//check one attribute
2let person = [{name: "john"}, {name: "jane"}, {name: "imelda"}, {name: "john"}];
3
4person = person.filter((item, index, self) =>
5 index === self.findIndex((t) => (
6 t.name === item.name
7 ))
8)
9
10//check two attributes
11let person = [{place: "uno", name: "john"}, {place: "duno", name: "jane"}, {place: "duno" ,name: "imelda"}, {place: "uno" ,name: "john"}];
12
13person = person.filter((item, index, self) =>
14 index === self.findIndex((t) => (
15 t.place === item.place && t.name === item.name
16 ))
17)
1var arrayWithDuplicates = [
2 {"type":"LICENSE", "licenseNum": "12345", state:"NV"},
3 {"type":"LICENSE", "licenseNum": "A7846", state:"CA"},
4 {"type":"LICENSE", "licenseNum": "12345", state:"OR"},
5 {"type":"LICENSE", "licenseNum": "10849", state:"CA"},
6 {"type":"LICENSE", "licenseNum": "B7037", state:"WA"},
7 {"type":"LICENSE", "licenseNum": "12345", state:"NM"}
8];
9
10function removeDuplicates(originalArray, prop) {
11 var newArray = [];
12 var lookupObject = {};
13
14 for(var i in originalArray) {
15 lookupObject[originalArray[i][prop]] = originalArray[i];
16 }
17
18 for(i in lookupObject) {
19 newArray.push(lookupObject[i]);
20 }
21 return newArray;
22 }
23
24var uniqueArray = removeDuplicates(arrayWithDuplicates, "licenseNum");
25console.log("uniqueArray is: " + JSON.stringify(uniqueArray));
1arr.reduce((acc, current) => {
2 const x = acc.find(item => item.id === current.id);
3 if (!x) {
4 return acc.concat([current]);
5 } else {
6 return acc;
7 }
8}, []);
1// BEST ANSWER - LINEAR TIME SOLUTION
2
3const seen = new Set();
4const arr = [
5 { id: 1, name: "test1" },
6 { id: 2, name: "test2" },
7 { id: 2, name: "test3" },
8 { id: 3, name: "test4" },
9 { id: 4, name: "test5" },
10 { id: 5, name: "test6" },
11 { id: 5, name: "test7" },
12 { id: 6, name: "test8" }
13];
14
15const filteredArr = arr.filter(el => {
16 const duplicate = seen.has(el.id);
17 seen.add(el.id);
18 return !duplicate;
19});
1const arr = [
2 { id: 1, name: "test1" },
3 { id: 2, name: "test2" },
4 { id: 2, name: "test3" },
5 { id: 3, name: "test4" },
6 { id: 4, name: "test5" },
7 { id: 5, name: "test6" },
8 { id: 5, name: "test7" },
9 { id: 6, name: "test8" }
10];
11
12const filteredArr = arr.reduce((acc, current) => {
13 const x = acc.find(item => item.id === current.id);
14 if (!x) {
15 return acc.concat([current]);
16 } else {
17 return acc;
18 }
19}, []);
20
1arr.filter((v,i,a)=>a.findIndex(t=>(t.place === v.place && t.name===v.name))===i)