Home > Back-end >  How To Return Values from one array when values from another array are selected by users in Javascri
How To Return Values from one array when values from another array are selected by users in Javascri

Time:09-22

I'm a new student of programming and I'm trying to figure out an assignment.

I have to write a function that returns values from one array when values from another array are selected by the user on a one-to-one basis.

I've tried the following among other things and it gives a reference error (Apple is not defined; but Apple is an element in the first array).

var valueFromSelect = Apple;

  for (var i = 0; i < fruits.length; i  ){
    if(valueFromSelect == fruits[i]){
      console.log(prices[i]);
      break

In short, I want to return a price for each fruit that is selected. Here are the arrays:

var fruits = ["Apple", "Orange", "Banana", "Pear", "Pineapple", "Strawberry", "Blueberry"];
var prices = [1.50, 1.20, 1.05, 1.10, 3.00, 0.40, 0.10]

Thank you.

CodePudding user response:

Apple value must be a string if your array contain strings.

var valueFromSelect = "Apple";
var fruits = ["Banana", "Orange", "Apple"];

PS : You can simplify your code by using filter method (from Array prototype) like bellow :

var valueFromSelect = "Apple";
var fruits = ["Banana", "Orange", "Apple"];
var result = fruits.filter(fruit => valueFromSelect == fruit);

This will return you an Array containing each values who matched with items in your Array. so if result.length > 0 you can consider your parameter as 'matched'.

CodePudding user response:

The error you are getting is because in order for JS to understand Apple is a string you have to surround it with " (double quotes) or ' (quotes).

The way it is right now, is telling JS to save into valueFromSelect the value stored in something called Apple which you have not defined yet.

Examples:

  • 'Apple'
  • "Apple"

This way it should work:

var valueFromSelect = 'Apple';

  for (var i = 0; i < fruits.length; i  ){
    if(valueFromSelect == fruits[i]){
      console.log(prices[i]);
      break
  • Related