DEV Community

Anjali Gurjar
Anjali Gurjar

Posted on

Method

Use Case Best Method Time Complexity Why?
Count occurrences of each element reduce() O(n) Efficient for counting
Get only elements that appear more than once filter() + Set O(n²) (can be slow for large arrays) Identifies duplicates
Remove duplicates (keep unique values) Set or filter() O(n) Set is fastest
Keep only elements appearing once filter() O(n²) Finds truly unique values
Group duplicates into arrays reduce() O(n) Organizes duplicates
Find first duplicate element Set + find() O(n) Fast and stops early
Remove duplicates without Set filter() + indexOf() O(n²)

const arr = ['2', '2', '2', '3', '3', '3', '4', '4'];

const grouped = arr.reduce((acc, item) => {
acc[item] = acc[item] ? [...acc[item], item] : [item];
return acc;
}, {});

console.log(grouped);
// Output: { '2': ['2', '2', '2'], '3': ['3', '3', '3'], '4': ['4', '4'] }

///inStcock. asd discount
const products = [
{ name: "Laptop", price: 800, inStock: true },
{ name: "Phone", price: 500, inStock: false },
{ name: "Tablet", price: 300, inStock: true }
]

const result = products.filter(product=> product.inStock).map(product=>({...product, price:product.price*0.9}))
console.log(result)

Top comments (0)