|
| 1 | +// Find non negative duplicates and how many times |
| 2 | + |
| 3 | +let array = [1, 4, -1, 8, 2, 4, 4, 4, 1, -1, 6, 2, 1, 9, 7]; |
| 4 | +function findDuplicates(arr) { |
| 5 | + let duplicateElements = {}; |
| 6 | + arr.forEach((currentValue, currentIndex) => { |
| 7 | + |
| 8 | + // return currentValue > 0 && arr.indexOf(currentValue) !== currentIndex; // return non negative and duplicate elements |
| 9 | + |
| 10 | + // find how many times |
| 11 | + if(currentValue > 0 && arr.indexOf(currentValue) !== currentIndex){ |
| 12 | + duplicateElements[currentValue] = (duplicateElements[currentValue] || 1) + 1; |
| 13 | + } |
| 14 | + |
| 15 | + // console.log(currentValue, currentIndex, arr.indexOf(currentValue)) |
| 16 | + }); |
| 17 | + |
| 18 | + |
| 19 | + return duplicateElements; |
| 20 | +} |
| 21 | + |
| 22 | +console.log(findDuplicates(array), Object.keys(findDuplicates(array))); |
0 commit comments