Lowtrux
Lowtrux

Reputation: 15

Javascript Find string in a table like array

This question have two parts: first, I want to create an array that works like a table. It will have two columns ids (Game-Id and Game-Name). I have been working in something like this:

var game_list = 
  [
    {id:1, name:'Vampires hunter'},
    {id:2, name:'Christmas vampires'},  
    {id:3, name:'Fruit hunter'},
    {id:4, name:'The fruitis'},
    {id:5, name:'james bond'},
    {id:6, name:'Vampires hunter'},
    {id:7, name:'Vampires avalon'},
    {id:8, name:'Vampires warrior'},
    {id:9, name:'Vampires hunter'}, 
    {id:10, name:'Vampires hunter'},
  ];

But I'm not able to access elements in this kind of array / object, not even a document.write of an element.

What I need is to create a function that will search for a specific string inside that array. The function will have 2 parameters (the string and the array) and it will give us a result an array of the elements with game names and ids that match that string.

Upvotes: 0

Views: 447

Answers (2)

Andy
Andy

Reputation: 63589

Use filter:

function filter(arr, string) {
  return arr.filter(function (el) {
    return el.name === string;
  });
}

filter(game_list, 'Vampires avalon'); // [{ id=7, name="Vampires avalon"}]

Demo

If you want to be really clever, add some regex to match the string anywhere in the name:

function filter(arr, string) {
  var regex = new RegExp('.*' + string + '.*');
  return arr.filter(function (el) {
    return regex.exec(el.name);
  });
}

filter(game_list, 'hunter');

Which will give you this:

[{"id":1,"name":"Vampires hunter"},{"id":3,"name":"Fruit hunter"},{"id":6,"name":"Vampires hunter"},{"id":9,"name":"Vampires hunter"},{"id":10,"name":"Vampires hunter"}]

Demo

Upvotes: 2

tymeJV
tymeJV

Reputation: 104795

A simple loop and check will do:

function checkArray(name) {
    var arr = [];
    for (var i = 0; i < game_list.length; i++) {
        if (game_list[i].name == name)
            arr.push(game_list[i])
    }
    return arr;
}

Will compare the name passed in with the name of each object, and returns an array of matching objects. If you only want names containing the passed in string, use indexOf and check on -1

Upvotes: 0

Related Questions