0

I am trying to delete a property name from the array of object, it's working properly using filter API,

const users = [
  { name: 'Tyler', age: 28},
  { name: 'Mikenzi', age: 26},
  { name: 'Blaine', age: 30 }
];


const myProp = users.filter(function (props) {
  delete props.name;
  return true;
});
console.table(myProp);
const myProp2 = users.reduce((people, user) => {
  console.log(people);
  console.log(user);
  delete user.name;
  return people;
}, []);

console.log(myProp2);

The same example before I am trying complete using reduce API, However, it's not working as expected.

2
  • This is not the intended use-case of reduce or filter for that matter. Just use forEach. Commented Jul 1, 2020 at 17:44
  • I am just using for the experiment purposes, learning how reduce work. Commented Jul 1, 2020 at 17:58

2 Answers 2

1

It's not working because your not pushing to the previous element (you are always returning the empty array). You need to change it to:

const myProp2 = users.reduce((people, user) => {
 delete user.name;
  people.push(user)
  return people;
}, []);

Please note that is not the intended use for reduce though - map is the operation you are looking for:

const myProp2 = users.map(u=> ({age: u.age}));
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your help, I am just using for the experiment purposes.
1

You actually want to use map for this, because you are selecting a transormation of the data into a new object (similar to Select in SQL or LINQ)

const myProps = users.map(u=> ({age: u.age}))

Also although the filter method worked, this is actually abuse of the filter method. The filter method is supposed to remove elements from the array depending on a condition. Your method worked because you returned true (which removed no elements) but you modified the current value on each iteration.

This is bad practice because you will confuse the next person to look at your code, they will wonder why you used filter as a method to transform the data rather than map.

Also don't use reduce because reduce is an aggregation function intended to perform aggregate functions on objects. Since the number of elements you are returning will be the same, map is better for this.

Reduce would be better suited for if you wanted to find out the average,max,min,median age or the most popular name etc...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.