Jump to content

.London Domains - £4
Photo

JavaScript Search/Array Methods...

javascript array methods arrays

  • Please log in to reply
1 reply to this topic

#1 historygirllfc

historygirllfc
  • Hefty Member
  • Advanced Member
  • 629 posts

Posted 17 June 2018 - 11:31

So I attempting to do a JS search thing (I have posted about it before...). I have an array of objects with info about football teams what I would like to do is be able to enter a team to seach for and if search name matches one of the teams show the relevant info about that team.

 

So far I have EventListener on the input to get the search value and created an array of the team names to match against. I have that removed the football club from the strings using replace, but I would like to further reduce the strings further and remove words from the strings as although some teams have united or city etc in their names it is not how they are usually referred to, although some do need to have that included.

 

I have looked through MDN and the list of array methods but not sure if the best way to approach it as some teams need that part of the name and others don't. Could it be splice? As the teams are listed alphabetically so I can get the index value and use that to target but could I use that for multiple teams/words?

 

Also to get the other info and display for the team that matched the search term I figure I want a for loop to go through the original teams array but not sure how it ties up with the other teamNames array I have created?

 

Any help appreciated... I think I understand the relevant bits as ever it tyings them all together I'm having difficulty with.

 

 

Codepen here:

https://codepen.io/cgweb/pen/zaEEqo


  • 0

YNWA


#2 Lyndsey

Lyndsey
  • Supporter+
  • Standard Member
  • 401 posts

Posted 16 July 2018 - 07:29

You'll probably want to use Array.filter to filter out teams based on the search keyword, rather than use a for loop. It's much cleaner:

const teams = [{ name: 'Wolves' //etc }];
const filteredTeams = teams.filter(team => team.name === searchTerm);

The string manipulation you are talking about seems a bit overkill. You could store the information in the object directly in another property e.g

const teams = [
  {
    name: 'West Bromwich Albian Football Club',
    shortName: 'West Brom',
    founded: 1878
  },
  {
    name: "Cardiff City Football Club",
    founded: 1899
  }
];

  • 1





Also tagged with one or more of these keywords: javascript, array methods, arrays

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users