简体   繁体   中英

How do I remove the objects I want from an array and add them to another array using .forEach?

This is a coding challenge I'm working on and can't seem to grasp what I need to do. Not sure if I am even going in the right direction.

Here is the instructions: Here we have an array called people. Some of them are our friends and some are not. 1. Create an empty array called friends. 2. Using .forEach, loop over people and add those that are our friend to the empty friends array.

Here is the provided code:

var people = [
  {name: "Landy",friend: true},
  {name: "Corey",friend: true},
  {name: "Ted",friend: false},
  {name: "Sperry",friend: true},
  {name: "Bill",friend: false}
];

My code so far:

var friends = [];
people.forEach(function(people){
  if (people === true) {
    return name;
  } else {
    // 
  }
});
var friends = [];
people.forEach(function(person){
  if (person.friend) friends.push(person)
});

One possible solution would be

var friends = [];
people.forEach(p => {
    if(p.friend)            // if person is a friend
        friends.push(p);    // push it to our friends array
});

// or

people.forEach(p => p.friend && friends.push(p));  // short-circuiting

We can also do this if we don't have to use .forEach

// use the key ".friend" as the condition
var friends = people.filter(p => p.friend);

Traditional way of doing it

var friends = [];
for(var i = 0; i < people.length; i++){
    p = people[i];          // get i-th people
    if(p.friend)            // if person is a friend
        friends.push(p);    // push it to our friends array
});

Example:

 var people = [ {name: "Landy",friend: true}, {name: "Corey",friend: true}, {name: "Ted", friend: false}, {name: "Sperry", friend: true}, {name: "Bill",friend: false} ]; var friends = []; people.forEach(p => { if(p.friend) friends.push(p); }); console.log(friends); 

This is a quick solution using $.grep();

var friends=$.grep(people,function(o){
                                  return o.friend;
                                     });

$.grep() returns array of object passed into the callback function that returns true

I would do this using #Array.prototype.filter. It's the easiest. You can also use #Array.prototype.map to transform "persons" to "names". Click the button to run the code below and see for yourself.

 var people = [ {name: "Landy",friend: true}, {name: "Corey",friend: true}, {name: "Ted",friend: false}, {name: "Sperry",friend: true}, {name: "Bill",friend: false} ]; var friends = people // only keep the people that are friends .filter(person => person.friend) // transform a person to a name .map(person => person.name); console.log(friends) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM