Javascript : What is the method to access the array index of a string?

Hey there, I'm struggling with changing a string to invoke an array in JavaScript. Can someone please help me out?

So, I have this array:

var fruit=['Apple','Banana','Orange'];

And I also have a data string from MySQL:

For example: var string = '0,2';

Can anyone advise on how to display the elements of the fruit array that correspond to the indices specified in the string variable?

(Any assistance would be greatly appreciated)

Answer №1

To obtain an array of indexes instead of a string of indexes, you need to use the split() method on the string:

var indexes = '0,2'.split(','); // Split the string using ',' as the delimiter

Next, you will need to retrieve the fruit values corresponding to each index in the newly created indexes array.

var juicyFruits = []; // Create a new array for the juicy fruits

indexes.forEach(function(index) { // Iterate over the desired fruit indexes

  juicyFruits.push(fruit[index]); // Add the delicious fruit :)

});

You now have a new array (juicyFruits) containing the succulent fruits :)

Try it out on JSFiddle

UPDATE:

Alternatively, a shorter and neater solution (credits to Xotic750) (the second argument in the map function specifies the context (this))

var indices = '0,2';
var fruitsArray = ['Apple','Banana','Orange'];

fruitsArray = indices.split(',').map(function(index) {
    return this[index];
}, fruitsArray);

Answer №2

Trying to solve this problem creatively, I came up with the following solution:

let numArr = [];
for (let j = 0; j <= inputStr.length; j += 2) {
 numArr.push(vegetable[inputStr[j]]);
}

Remember to only select even numbers because there are commas in the string as well.

Answer №3

To break down the text into a list, you should utilize the Break() function:

let myArray = text.break(",");

Next, iterate through the list and access its elements as indices in the food list. For instance, the first item would be:

food[myArray[0]];

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

leveraging dependency injection to retrieve a function in JavaScript

I'm exploring a way to obtain a function in JavaScript without executing it, but still defining the parameters. My current project involves creating a basic version of Angular's dependency injection system using Node.js. The inject() method is us ...

What is the best way to convert an array JSON into a PHP Object?

I encountered an issue while trying to convert my JSON array into a PHP object using a foreach loop. Here is the error message I received: Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\testJSON\crul_json.php ...

Trouble with two dropdown selections in Angular and preset values

I am encountering an issue with a select input in angular 7. The scenario involves having 2 selects where selecting an option in the second select populates the corresponding values in the first select. The first select should display a default placeholder ...

Is there an obstacle hindering the load event?

There's something strange happening on a website I created. The page content loads in 5 or 6 seconds, but the DOMContentLoaded and Load Event don't actually fire until 1 minute and 10 seconds later. When I reload the page during loading, it load ...

Overcoming the __proto__ constraint in Internet Explorer 9 and 10

Hey there Javascript wizards! I've got a tricky problem on my hands and can't seem to find a solution that satisfies me. I'm working on a specific JavaScript framework where I need to set the __proto__ property of a dynamically created func ...

What is the best way to sort through the items in a dropdown menu?

Can you help me with a scenario where I need to filter elements in a dropdown based on input given in a text box? I have tried using ng-change but it doesn't seem to work. Is there another way to achieve this? Here is the HTML code snippet: <inpu ...

Tips for effectively utilizing JavaScript regex to precisely match a string before triggering the submit button

I have a form in Angular with a text input field that requires the entry of lowercase letters separated by commas, like this: c, d, e, g, a, f etc... Currently, the submit button activates as soon as any part of the input matches the required format, allo ...

Protractor Cucumber: Issue with locating spec file patterns (identifying 2 features)

I am facing an issue with running 2 different cucumber features. After adding the following lines to my protractor.conf.js file: specs: ['add.feature', 'delete.feature'] I encountered a problem when running the tests stating pattern ...

Issues have arisen due to server calls being affected by AngularJS routing

I have implemented AngularJS in a nodewebkit application. There are three main views: Home.html Conversation.html Login.html Upon login, the following code is executed: $state.go('home.main'); which triggers the following state c ...

The Javascript document refuses to load

I am currently working on a website with the main file named index.html: <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>Title</title> </head> ...

Navigating Through Objects

Currently, I am utilizing the Jquery Dropdown Plugin and ListJS Plugin for my project. The jQuery Dropdown Plugin features a hide event: $('.dropdown').on('hide', function(event, dropdownData) { }); Within this event, I am integratin ...

Error with JSON data from the Twitch TV API

I am having trouble with the Twitch API. When a streamer is live, I work with the "Stream" property, but if they are not streaming, I need to refer to another link. I use the getJSON function to fetch the necessary API link and work with it. However, my lo ...

Attempting to display the todo item in the form of <li>, however, the todo.name property is not

I am currently developing a task manager application and have encountered a puzzling issue: When I include the Todo component within the TodoList component and pass the todo item as a prop todo = {name: "ssss", status: false, id: 0.0289828650088 ...

"Uncaught ReferenceError: Rawdata.some is not defined, and a table design

Currently, I am in the process of developing a basic table using data retrieved from the backend via an API call with Ant Design in React. The version of Ant Design I am using is: "antd": "^5.1.1", My approach involves making an API ...

Developing a Multi-Faceted Array Utilizing SQL Data

The requirement of the plugin I am using is to provide it with an array structure in JavaScript that looks like this: var data = [ { "id": 1, "name": "University1", "list": [ {"id": 1, "name": "Dorms", "list": ...

Steps to dynamically populate a datatable with JSON data by triggering a click event in jQuery

I am facing an issue with feeding JSON data into datatables when the search button is clicked. The JSON data structure is as follows: [ { "port_code":"BOM", "cont_details_id":"9", "price":"44.000", "cont_price":"500", "c ...

An error of '______ is not defined' was thrown, I'm puzzled as to why

I keep encountering an error that says "weekday is not defined". I'm unsure of the reason behind this issue. Any assistance would be greatly appreciated! (function(exports) { var days = ["monday", "tuesday", "wednesday", "thursday"]; exports. ...

methods for retrieving specific key values in javascript

I have an Object containing the following data: const fruits = { apple: 28, orange: 17, pear: 54, }; The goal is to extract and insert the value from the key "apple" into an empty array. While using Object.values.fruits provides all the value ...

Changing Underscores in ES6 Techniques

My current project is built using AngularJS, Redux, and Underscore. Within this project, I have the following code snippet: const selectedBroker = _.findWhere(state.brokers, { brokerId: action.payload }); return state.merge({ selectedBroker, sel ...

Route fallback not yet resolved

Is it possible to set up a fallback route in angular routes? For instance, is there a way to specify a fallback route like this: $routeProvider .when('/a', { templateUrl: 'a.html', controller: 'aCtrl' ...