-2

I wanted to find the usernames with '!' and '?' in an objects array and store them in a new array.

The objects array is as follows.

const array = [
  {
    username: "john!",
    team: "red",
    score: 5,
    items: ["ball", "book", "pen"]
  },
  {
    username: "becky",
    team: "blue",
    score: 10,
    items: ["tape", "backpack", "pen"]
  },
  {
    username: "susy?",
    team: "red",
    score: 55,
    items: ["ball", "eraser", "pen"]
  },
  {
    username: "tyson",
    team: "green",
    score: 1,
    items: ["book", "pen"]
  },

];

I tried the test() method with forEach looping, but I couldn't get the preferred output. How can I do it? Can I use map() instead of forEach to iterate through objects?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

5 Answers5

1

Solution

Here is a simple single-line solution to your problem:

const arr = [
  {
    username: "john!",
    team: "red",
    score: 5,
    items: ["ball", "book", "pen"]
  },
  {
    username: "becky",
    team: "blue",
    score: 10,
    items: ["tape", "backpack", "pen"]
  },
  {
    username: "susy?",
    team: "red",
    score: 55,
    items: ["ball", "eraser", "pen"]
  },
  {
    username: "tyson",
    team: "green",
    score: 1,
    items: ["book", "pen"]
  },

]

let newArr = []

arr.forEach(({username}) => username.match(/[?|!]/g) ? newArr.push(username) : null)

console.log(newArr)

How it works

First, we loop through all of the elements in the array using:

arr.forEach(({username}) => ...)

Then we check to see if the username contains a '!' or '?' using a regular expression (regex):

username.match(/[?|!]/g)

If it does contain a '?' or '!' then push the username to a new array:

newArr.push(username)

If the username does not match, return null.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Fletcher Rippon
  • 1,837
  • 16
  • 21
0

const array = [
  {
    username: "john!",
    team: "red",
    score: 5,
    items: ["ball", "book", "pen"]
  },
  {
    username: "becky",
    team: "blue",
    score: 10,
    items: ["tape", "backpack", "pen"]
  },
  {
    username: "susy?",
    team: "red",
    score: 55,
    items: ["ball", "eraser", "pen"]
  },
  {
    username: "tyson",
    team: "green",
    score: 1,
    items: ["book", "pen"]
  },
];

const usernames = array
  .filter(({ username }) => /\?|!/.test(username))
  .map(({ username }) => username);

console.log(usernames);
ElectricShadow
  • 683
  • 4
  • 16
0

Specific to your use case this is how you would get all the usernames that contain those characters.

Array.filter creates a new array so you dont have to mutate the original one to get the values you want.

array.filter(obj => obj.username.includes("!") || obj.username.includes("?"))
Grant Herman
  • 923
  • 2
  • 13
  • 29
  • Only use snippets for working examples with output. Otherwise, use code blocks instead. Also, when you have multiple string tests, it is usually cleaner to use a regular expression. In this case, `/\?|!/` works fine. Lastly, the array should include usernames, not entire objects. – ElectricShadow Nov 06 '20 at 15:14
  • I like this shorthand way of doing it. Thanks! – Kanchana_Kumari Nov 06 '20 at 15:46
0

I think this should do the job.

const names = array.reduce((acc, item) => {
  if (/[!?]$/.test(item.username)) {
    acc.push(item.username);
  }
  return acc;
}, []);
Sergey
  • 1,000
  • 8
  • 19
0

Use Array.prototype.filter() in order to filter out the objects whose username includes ! or ? or other characters which you want to check for into a new array.

 const array = [
      {
        username: 'john!',
        team: 'red',
        score: 5,
        items: ['ball', 'book', 'pen'],
      },
      {
        username: 'becky',
        team: 'blue',
        score: 10,
        items: ['tape', 'backpack', 'pen'],
      },
      {
        username: 'susy?',
        team: 'red',
        score: 55,
        items: ['ball', 'eraser', 'pen'],
      },
      {
        username: 'tyson',
        team: 'green',
        score: 1,
        items: ['book', 'pen'],
      },
    ];
    
    const filteredArray = array.filter(object => {
//You need to add your characters in the below condition to check for them I have //added for ! & ? for now
      return object.username.includes('!') || object.username.includes('?'); 
    });
    console.log(filteredArray);

//To get just the usernames
filteredArray.forEach(object => console.log(object.username));
Link
  • 1,198
  • 4
  • 14