Ask Your Question
0

How can unique items be obtained from the result of mapping and filtering an array using JavaScript?

asked 2021-10-09 11:00:00 +0000

bukephalos gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-08-15 10:00:00 +0000

lalupa gravatar image

There are several ways to obtain unique items from the result of mapping and filtering an array in JavaScript:

  1. Using the Set object: After mapping and filtering an array, we can create a new Set object and pass the resulting array as its argument. The Set object automatically removes duplicates and returns only unique values.

Example:

const arr = [3, 2, 2, 1, 4, 3];
const uniqueArr = [...new Set(arr.map(item => item * 2).filter(item => item > 4))];
console.log(uniqueArr); // Output: [6, 8]
  1. Using the filter method with the indexOf method: We can use the filter method to iterate through the array and return only the elements that are not already present in the new array.

Example:

const arr = [3, 2, 2, 1, 4, 3];
const uniqueArr = arr.map(item => item * 2).filter((item, index, self) => self.indexOf(item) === index && item > 4);
console.log(uniqueArr); // Output: [6, 8]
  1. Using the reduce method with an empty array: We can use the reduce method to iterate through the array and add only non-duplicate elements to a new empty array.

Example:

const arr = [3, 2, 2, 1, 4, 3];
const uniqueArr = arr.map(item => item * 2).filter(item => item > 4).reduce((acc, item) => {
  if (!acc.includes(item)) {
    acc.push(item);
  }
  return acc;
}, []);
console.log(uniqueArr); // Output: [6, 8]

All three methods will return an array containing only unique values after mapping and filtering the original array.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-10-09 11:00:00 +0000

Seen: 8 times

Last updated: Aug 15 '21