Mamunur Rashid
Mamunur Rashid

Reputation: 1185

Remove a property from array of object using reduce API

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.

Upvotes: 0

Views: 957

Answers (2)

Max Carroll
Max Carroll

Reputation: 4839

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...

Upvotes: 1

eol
eol

Reputation: 24565

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}));

Upvotes: 1

Related Questions