Interview Questions- Part-8

First duplicate value occurence using Map

				
					const num = [1, 2, 3, 4, 2, 3, 4, 6, 8];
let map = new Map();
let output = num.map((item) => {
  if (map.has(item)) {
    return item;
  }
  map.set(item);
});
//output - [undefined, undefined, undefined, undefined, 2, 3, 4, undefined, undefined]
console.log(output.find((i) => i));
				
			

First duplicate value occurence using Filter

				
					const num = [1, 2, 3, 4, 2, 3, 4, 6, 8];
let map = new Map();
let output = num.filter((item) => {
  if (map.has(item)) {
    return item;
  }
  map.set(item);
});
//output - [2, 3, 4]
//This also fetches you all duplicates in the array- 2 3 4
console.log(output[0]);
				
			

First duplicate value occurence using Find

				
					const num = [1, 2, 3, 4, 2, 3, 4, 6, 8];
let map = new Map();
let output = num.find((item) => {
  if (map.has(item)) {
    return item;
  }
  map.set(item);
});
//output - 2
//This fetches you 2
console.log(output);
				
			

First duplicate value occurence using Every

				
					const num = [1, 2, 3, 4, 2, 3, 4, 6, 8];
let map = new Map();
let final;
let output = num.every((item) => {
  if (map.has(item)) {
    final = item;
    return false;
  }
  map.set(item);
  return true;
});

console.log(final);

				
			

First duplicate value occurence using some

				
					const num = [1, 2, 3, 4, 2, 3, 4, 6, 8];
let map = new Map();
let final;
let output = num.some((item) => {
  if (map.has(item)) {
    final = item;
    return true;
  }
  map.set(item);
});
// //output - 2
 console.log(final);
				
			

Leave a Comment