Gingervitus
Gingervitus

Reputation: 21

Creating a function for an array in javascript.

Hey just starting javascript and having some trouble writing a function for two arrays. One is an array of names and one is an array of quotes. I'm not going to write out every name and every quote but it's laid out as such.

Names = [Jim, Bob, Josh, Tom]

Quotes = [
[ "blah blah blah."
"quote quote quote."] 
] 

Now each array of quotes corresponds with the name so since Jim would be [0] in the names array his quotes would also be [0]. I was trying to create a function where you would be able to input something like numberofQuotes("Jim") and have it spit out how many quotes that person had. But I can't figure out how to do it. I'm still largely a novice at Javascript.

Upvotes: 1

Views: 46

Answers (2)

bhansa
bhansa

Reputation: 7504

Create a key:value pair by iterating and assigning the value to the key according the first array.

Later you can check the number of quotes: Obj["Jim"].length

var Names = ['Jim', 'Bob', 'Josh', 'Tom']

var Quotes = [
  ["blah blah blah.", "Jim again"],
  "quote quote quote.", "Josh quoted", "Tom quoted"
]

var Obj = {}

for (var i = 0; i < Names.length; i++) {
  Obj[Names[i]] = Quotes[i];
}

console.log("Jim quoted", Obj["Jim"].length);

Upvotes: 0

Cjmarkham
Cjmarkham

Reputation: 9681

You can achieve this using indexOf and length.

var names = ['Jim', 'Carl', 'Bob'];
var quotes = [['Foo bar', 'Something smart'], ['something dumb'], []];

function countQuotes (name) {
  // indexOf will return the position the name appears in the names array
  var index = names.indexOf(name);
  // we can use it to get the same position in the quotes array
  // length returns how many items are in the array
  return quotes[index].length;
}

var result = countQuotes('Jim');
console.log(result);

However, as stated in the comments, an object would be a good use for this:

var people = {
  Jim: [
    'Foo bar',
    'Something smart',
  ],
  Carl: [
    'Something dumb',
  ]
};

var countQuotes = function (name) {
  return people[name].length;
}

var result = countQuotes('Jim');
console.log(result);

There are a few more ways to format the object but I will let you experiment.

Upvotes: 1

Related Questions