1

Assuming an array containing student's names and their respective score, I want to retrieve the score of certain student (by checking if the array element contains the student's name (string))

I came up with this but it doesn't work

var students = [
  ['David', 80],
  ['Dane', 77],
  ['Dick', 88],
  ['Donald', 95],
  ['Dean', 68]
];


function test() {
  for (var i = 0; i < students.length; i++) {
    var name = document.getElementById("namebox").value;
    var string = students[i].toString();
    if (string.includes(name);) {
      alert(students[i][1]);
    }
  }
};
<input type="text" id="namebox" /><button type="button" onclick="test()">Click</button>

3
  • your array structure should contain data property_name:property_value format,then you can use indexOf on property_name. Commented Jan 14, 2017 at 9:49
  • thanks a billion anyhow! Commented Jan 14, 2017 at 10:10
  • what do you want with more than one result? Commented Jan 14, 2017 at 10:34

3 Answers 3

4

You are doing students[i].toString(). This will return only a string which contains the items of the array. So suggest you don't do the toString and iterate over each item and use indexing. And also inside the first array you can contain objects of students, it will be more logically.

Move the

var namebox = document.getElementById("namebox");

out of the for loop. Every time engine spend a time to find the element in the for loop. So you get it once and use many times.

ES6 syntax

let students = [
    {name: 'David', score: 80},
    {name: 'Dane', score: 77},
    {name: 'Dick', score: 88},
    {name: 'Donald', score: 95},
    {name: 'Dean', score: 68}
];

let namebox = document.getElementById("namebox");

function test(){
  
   let name = namebox.value;

   students.forEach(item => {

     if(item.name.includes(name)){
       console.log(name, item.name, item.score);
     }

  });
  
}
<input type="text" id="namebox" />
<button type="button" onclick="test()">Click</button>

ES5 syntax

var students = [
        {name: 'David', score: 80},
        {name: 'Dane', score: 77},
        {name: 'Dick', score: 88},
        {name: 'Donald', score: 95},
        {name: 'Dean', score: 68}
    ];

var namebox = document.getElementById("namebox");

function test(){
  
   var name = namebox.value;

   for(var i = 0; i < students.length; i++){

      if(students[i].name.indexOf(name) !== -1)  {
         console.log(name,students[i].name,students[i].score);
      }

   }
  
}
<input type="text" id="namebox" />
<button type="button" onclick="test()">Click</button>

Sign up to request clarification or add additional context in comments.

Comments

1

Your code should work, except for the syntax error in the if condition, which has a ; that should not be there. Remove it and it works:

var students = [
    ['David', 80],
    ['Dane', 77],
    ['Dick', 88],
    ['Donald', 95],
    ['Dean', 68]
];

function test(){
    for (var i = 0; i < students.length; i++) {
        var name = document.getElementById("namebox").value;
        var string = students[i].toString();
        if (string.includes(name))
        {
          console.log(students[i][1]);
        }
    }
};
<input type="text" id="namebox" /><button type="button" onclick="test()">Click</button>

But there are some inefficiencies in your code:

  • Don't read out the input value in every iteration of the loop, you just need to do this once.
  • Instead of converting the pair students[i] to string, it seems more to the point to just look at students[i][0], which is a string already
  • Since you are using .includes() and thus are running on a modern browser, why not use the other features available in ES6, like .find()?

Here is the same with more efficient ES6 code:

const students = [
    ['David', 80],
    ['Dane', 77],
    ['Dick', 88],
    ['Donald', 95],
    ['Dean', 68]
];

const box = document.getElementById("namebox");

function test(){
    const value = box.value;
    const match = students.find(student => student[0].includes(value));
    if (match) {
      console.log(match[1]);
    }
};
<input type="text" id="namebox" /><button type="button" onclick="test()">Click</button>

2 Comments

@mplungjan, OK so now my answer makes no sense anymore? I am not sure you should answer questions by fixing them ;-)
I put the typo back ;)
1

You could use Array#filter and return an array with the matched names.

function getStudentsByName() {
    var name = document.getElementById("namebox").value.toLowerCase();
    document.getElementById("out").innerHTML = JSON.stringify(students.filter(function (a) {
        return a[0].toLowerCase() === name;
    }), 0, 4);
}

var students = [['David', 67], ['David', 80], ['Dane', 77], ['Dick', 88], ['Donald', 95], ['Dean', 68]];
<input type="text" id="namebox" /><button type="button" onclick="getStudentsByName()">Click</button>
<pre id="out"></pre>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.