|
| 1 | +// Unique Values |
| 2 | +// Write a function that takes in two arrays and returns an array of the unique values |
| 3 | + |
| 4 | +// not bad, but all unique values are used as object keys, so when put back into an array they're all strings, and out of original order |
| 5 | +const uniqueValuesObj = (arr1, arr2) => { |
| 6 | + const allValues = [...arr1, ...arr2] |
| 7 | + const tempObj = allValues.reduce((obj, val) => { |
| 8 | + if (obj[val]) { |
| 9 | + obj[val]++ |
| 10 | + } else { |
| 11 | + obj[val] = 1 |
| 12 | + } |
| 13 | + return obj |
| 14 | + }, {}) |
| 15 | + |
| 16 | + return Object.entries(tempObj) |
| 17 | + .filter(el => el[1] === 1) |
| 18 | + .map(el => el[0]) |
| 19 | +} |
| 20 | + |
| 21 | +console.log(uniqueValuesObj([1, 2, 3, 5], [1, 2, 3, 4, 5])) |
| 22 | +console.log(uniqueValuesObj([1, 'calf', 3, 'piglet'], [7, 'filly'])) |
| 23 | +console.log(uniqueValuesObj([2, 1, 3], [3, 2, 1])) |
| 24 | + |
| 25 | +// |
| 26 | +// |
| 27 | +// using Map instead of an object, which returns all values as they original type, and in the same order |
| 28 | +const uniqueValuesMap = (arr1, arr2) => { |
| 29 | + const allValues = [...arr1, ...arr2] |
| 30 | + const uniqueValMap = allValues.reduce((tempMap, val) => { |
| 31 | + if (tempMap.has(val)) { |
| 32 | + tempMap.set(val, tempMap.get(val) + 1) |
| 33 | + } else { |
| 34 | + tempMap.set(val, 1) |
| 35 | + } |
| 36 | + return tempMap |
| 37 | + }, new Map()) |
| 38 | + |
| 39 | + return Array.from(uniqueValMap.entries()) |
| 40 | + .filter(el => el[1] === 1) |
| 41 | + .map(el => el[0]) |
| 42 | +} |
| 43 | + |
| 44 | +console.log(uniqueValuesMap([1, 2, 3, 5], [1, 2, 3, 4, 5])) |
| 45 | +console.log(uniqueValuesMap([1, 'calf', 3, 'piglet'], [7, 'filly'])) |
| 46 | +console.log(uniqueValuesMap([2, 1, 3], [3, 2, 1])) |
| 47 | + |
| 48 | +// |
| 49 | +// |
| 50 | +// Using loops (good, but technically not most efficient) |
| 51 | +const uniqueValuesLoops = (arr1, arr2) => { |
| 52 | + const uniqueArr = [] |
| 53 | + |
| 54 | + for (const val of arr1) { |
| 55 | + if (!arr2.includes(val) && !uniqueArr.includes(val)) { |
| 56 | + uniqueArr.push(val) |
| 57 | + } |
| 58 | + } |
| 59 | + for (const val of arr2) { |
| 60 | + if (!arr1.includes(val) && !uniqueArr.includes(val)) { |
| 61 | + uniqueArr.push(val) |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + return uniqueArr |
| 66 | +} |
| 67 | + |
| 68 | +console.log(uniqueValuesLoops([1, 2, 3, 5], [1, 2, 3, 4, 5])) |
| 69 | +console.log(uniqueValuesLoops([1, 'calf', 3, 'piglet'], [7, 'filly'])) |
| 70 | +console.log(uniqueValuesLoops([2, 1, 3], [3, 2, 1])) |
0 commit comments