-3
var name = document.getElementById("namebox").value;

if (array.includes(name) == false) {
   alert(name + " is not in record.")
}

that didn't work and will always return false, how to express the check in other ways? please enlighten, thank you very much

Nate
  • 161
  • 1
  • 1
  • 12

2 Answers2

3

You may try

if (array.indexOf(name) == -1) {
   alert(name + " is not in record.")
}
M. H
  • 46
  • 5
3

because your array is like

[ "name1,score1", "name2,score2"]

searching for "name1" using includes wont work

you'll want something like

if (!array.some(item => item.split(',')[0] === name)) {
    alert(name + " is not in record.")
}

or in pre ES2015

if (!array.some(function (item) {
    return item.split(',')[0] === name;
})) {
    alert(name + " is not in record.");
}

or if your browser doesn't have Array.prototype.some

if (array.filter(function (item) {
    return item.split(',')[0] === name;
}).length === 0) {
    alert(name + " is not in record.");
}
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
  • Read array.prototype.some documentation – Jaromanda X Jun 09 '17 at 05:13
  • The arrow function odd probably alien to you as well. Right – Jaromanda X Jun 09 '17 at 05:14
  • I've added some possibly easier to understand code - `item` could be any name, it's just each entry in the array for each iteration of `.some` – Jaromanda X Jun 09 '17 at 05:23
  • I was guessing... array is the name of the array students[]... and item is the element of the array... students[i][0] ?... and I will have to put them in a loop to check? – Nate Jun 09 '17 at 05:27
  • dear @Jaromanda X, I failed to understand how to use your methods just by reading documentation (language barrier and intelligence difference may be), but I managed to think of a way that is by constructing a temporary Array and then push all the student[i][0] (names) into it, then only do the checking... other than splitting method you tried to teach me, I also found array flattening methods but I really couldn't understand just by reading... thanks anyhow =) – Nate Jun 09 '17 at 08:08
  • to be honest, your original design is flawed. Rather than adding "name, score" onto an array, I would be adding an object something like `{student: "name", score: number}` - that way you can find the student using `array.find(item=> item.student === name)` – Jaromanda X Jun 09 '17 at 08:35
  • I've never used object before and it's the next topic I will start learning =) thanks – Nate Jun 09 '17 at 08:37