xxxxxxxxxx
function lonelyinteger(a: number[]): number {
for (let item of a) {
const items = a.filter(el => item === el)
if (items.length === 1) {
return item
}
}
}
const a:number[] = [1,2,3,4,3,2,1]
const result:number = lonelyinteger(a);
console.log(result)
xxxxxxxxxx
const myArray = ['a', 'b', 'c', 'c', 'b', 'd'];
const elementCounts = {};
myArray.forEach(element => {
elementCounts[element] = (elementCounts[element] || 0) + 1;
});
console.log(elementCounts);
//output
/*{
a: 1,
b: 2,
c: 2,
d: 1
}*/
xxxxxxxxxx
const numbers = [1, 2, 3, 2, 4, 5, 5, 6];
const set = new Set(numbers);
const duplicates = numbers.filter(item => {
if (set.has(item)) {
set.delete(item);
} else {
return item;
}
});
console.log(duplicates);
// [ 2, 5 ]
xxxxxxxxxx
function findDuplicates(arr) {
const duplicates = new Set()
return arr.filter(item => {
if (duplicates.has(item)) {
return true
}
duplicates.add(item)
return false
})
}
xxxxxxxxxx
const order = ["apple", "banana", "orange", "banana", "apple", "banana"];
const result = order.reduce(function (prevVal, item) {
if (!prevVal[item]) {
// if an object doesn't have a key yet, it means it wasn't repeated before
prevVal[item] = 1;
} else {
// increase the number of repetitions by 1
prevVal[item] += 1;
}
// and return the changed object
return prevVal;
}, {}); // The initial value is an empty object.
console.log(result); // { apple: 2, banana: 3, orange: 1 }
xxxxxxxxxx
public class Main {
public static void main(String[] args) {
int[] arr1 = {1,2,3,3,4};
for (int i = 0; i < arr1.length-1 ; i++) {
for (int j = 0; j < arr1.length; j++) {
if (arr1[i]==arr1[j] && (j != i)){
System.out.println("array's duplicate number: " +
arr1[j]);
}
}
}
}
}