📜  javascript es6 filter sum distinct - Javascript (1)

📅  最后修改于: 2023-12-03 15:31:37.197000             🧑  作者: Mango

JavaScript ES6 Filter, Sum, and Distinct

JavaScript ES6 provides us with powerful methods to manipulate arrays in a more concise and expressive way. Three of these methods that are particularly useful are filter, reduce, and Set.

Filter

The filter method allows us to create a new array with all the elements that pass the test implemented by the provided function.

const numbers = [1, 2, 3, 4, 5, 6];

const evenNumbers = numbers.filter(number => number % 2 === 0);

console.log(evenNumbers); // [2, 4, 6]

In this example, we create an array of numbers from 1 to 6 and use the filter method to create a new array evenNumbers that contains only even numbers.

Sum

The reduce method allows us to apply a function to each element of the array in order to reduce it to a single value. We can use it to sum up all the elements of an array.

const numbers = [1, 2, 3, 4, 5, 6];

const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);

console.log(sum); // 21

In this example, we use the reduce method to sum up all the elements of the numbers array. The second argument 0 is the initial value of the accumulator.

Distinct

The Set object allows us to create collections of unique values. We can use it to remove duplicates from an array.

const numbers = [1, 2, 3, 2, 4, 3, 5, 6, 1];

const distinctNumbers = [...new Set(numbers)];

console.log(distinctNumbers); // [1, 2, 3, 4, 5, 6]

In this example, we create an array of numbers with some duplicates and use the Set object to create a new array distinctNumbers with only unique values.

Conclusion

These methods provide us with powerful tools to manipulate arrays in JavaScript ES6. By using them, we can write more concise, expressive, and efficient code.