Javascript : How do I call the array index of the string? - javascript

Hello I have a problem when you change the string in order to invoke an array in javascript, please help me,
I have had a array:
var fruit=['Apple','Banana','Orange'];
and I have data string from mysql:
example: var string = '0,2';
How to display an array of fruit which corresponds to the var string?
(Thanks for the help)

You have to split() the string to get an array of indexes instead of a string of indexes :
var indexes = '0,2'.split(','); //use the ',' char to split the string
Now, you have to pick fruits values corresponding to each index in the new indexes array create just before.
var res = []; //The new Array to contains new fruits
indexes.forEach(function(index) { //loop over fruit indexes we want
res.push(fruit[index]); //Add the juicy fruit :)
});
And you got the new array (res) with the juicy fruits :)
JSFiddle
EDIT:
Or, a shorter/nicer solution (thanks to Xotic750)
(the second argument of the map function specify the context (this))
var ids = '0,2';
var fruits = ['Apple','Banana','Orange'];
fruits = ids.split(',').map(function(index) {
return this[index];
}, fruits);

I don't know if it will work or not, but this is what I could think of:
var x = [];
for (var i = 0; i>=string.length; i+=2) {
x.push(fruit[string[i]]);
}
But use only even numbers as a comma is also present in the string.

You will need to split the string into an array by using the Split() method:
var myArray = string.split(",");
Then you can loop over the array and use its values as indexes in the fruit array. For example, the first fruit will be:
fruit[myArray[0]];

Related

Is it possible to split a nested array to two arrays in Js

I'm getting a array like this
var cars = [['BMW'],[],['6000cc']];
which contains two different values of a same instance. Here you can see an empty array that's where the data changes. Basically the left side of the empty array contains one set of data and right side of the empty array contains other set of data.
I need to split this array in to two.
So you need to split array into two which is separated by empty array.
First you have to find the index of empty array.
var cars = [['BMW'],[],['6000cc']];
var index = -1
for(var i=0;i<cars.length;i++){
if(cars[i].length === 0)
{
index = i;
break;
}
}
then you can use slice to split array
var arr1 = cars.slice(0, index);
var arr2 = cars.slice(index+1);
You can use ES6 Array De-structuring and split your arrays.
let cars = [['BMW'],[],['6000cc']];
let [cname, other, cpower] = cars;
console.log(cname, cpower);

Array values to a string in loop

I have an object (key value pair) looks like this
I want to get a string of '[100000025]/[100000013]'
I can't use var str = OBJ[0].PC + OBJ[1].PC (which gives me '100000025100000013')
because I need the bracket structure.
The number of items can vary.
Added >> Can it be done without using arrow function?
const string = array.map(({PC}) => `[${PC}]`).join('/')
You could map every string to the string wrapped in brackets, then join that by slashes.
You can use a map() and a join() to get that structure. - this is hte same solution as Puwka's = but without the template literal.
var data = [
{am: 1, ct: "", pc: "1000000025"},
{am: 2, ct: "", pc: "1000000013"}
];
let newArr = data.map(item => "[" + item.pc +"]");
console.log(newArr.join("/")); // gives [1000000025]/[1000000013]
You can always use classic for in loop
let arr = [{PC:'1000'},{PC:'10000'}]
let arrOut = [];
for(let i = 0; i < arr.length; i++) {
arrOut.push('[' + arr[i].PC + ']');
}
now the arrOut is equal ["[1000]", "[10000]"] what we need is to convert it to a string and add '/' between items.
let str = arrOut.join('/');
console.log(str) // "[1000]/[10000]"
So you need a string in the format of: xxxx/yyyyy from a complex object array.
const basedata = [...];
const result = basedata.map( item => `[${item.PC}]` ).join('/')
so i will explain it now. The map function will return a new array with 1 entry per item. I state that I want PC, but i added some flavor using ticks to inject it inbetween some brackets. At this point it looks like: ["[1000000025]","[100000013]"] and then join will join the arrays on a slash, so it will turn into an array.
"[100000025]/[100000013]"
Now, this will expand based on the items in your basedata. So if you have 3 items in your basedata array, it would return:
"[10000000025]/[100000013]/[10000888]"
First if you want to divide the result then it will be better to change it into number and then just do the division.
Example
Number.parseInt("100000025")/Number.parseInt("100000013")
If you want to display it then better to use string interpolation
surround it with back tick
[${[0].PC}]/[${[1].PC}]
Hope this is what are you looking for

How can I split a string and then push something into the resulting array?

I have this string:
var fruits = "banana,apple";
And I'm trying to add fruits to it by converting it to an array and then pushing the new fruit like this:
var newFruit = "orange";
fruits
.split(",")
.push(newFruit);
But this doesn't work because fruits.split(",") doesn't seem to return a "normal" array, i.e I can't perform push() on it.
Is this somehow possible?
split does return a normal array. You are successfully calling push on it.
The problem is that you are then discarding the array so you can't do anything further with it.
Since push doesn't return the array itself, you have no way of using the array for anything further after calling push on it.
concat returns a new array that contains the additional values, but you would still have to do something with the array afterwards.
var fruits = "banana,apple";
var newFruit = "orange";
var myArray = fruits
.split(",")
.concat(newFruit);
console.log(myArray);
Array.prototype.push returns the new length of the array:
Return value:
The new length property of the object upon which the method was
called.
MDN Source
Also, you're not storing your new value. If you want to use push, here's how you'd do it:
var fruits = "apple,banana";
var newFruits = fruits.split(","); // Store the new array
newFruits.push("orange"); // Add the new item
console.log(newFruits);
If you want to do it in one line, you can use concat:
var fruits = "apple,banana";
var newFruits = fruits
.split(",") // Convert string to array
.concat("orange"); // Create a new array joined with value
console.log(newFruits);
push returns the new length of the array, because you are not saving it then you cant see the new array(after push)
try doing it in two lines:
newFruits = fruits.split(",");
newFruits.push(newFruit);

Output strings to arrays and output items from array

I'm sure this is really simple but I am learning Javascript and I can't figure this out.
var niceDay = "please, have a nice day";
How do I create an array using "niceDay", and output the array?
how do I output the item in index 2?!
Match the non-whitespace:
niceday.match(/\S+/g);
You can use the 'split' javascript function. This will split a string on a certain character and return an array:
var array = niceDay.split(' ');
This will return an array split on each space in the string.
You can then access the second item in the array using:
var item = array[1];
Or assign the second item a new value using:
array[1] = 'string';
Well this should be simple, that's true
Here's a solution
var niceDay = "please, have a nice day";
var niceDarray = niceDay.split(' '); // splits the string on spaces
// alerts each item of the array
for (var i = 0; i < niceDarray.length; i++) {
alert(niceDarray[i]);
}

Using JavaScript's split to chop up a string and put it in two arrays

I can use JavaScript's split to put a comma-separated list of items in an array:
var mystring = "a,b,c,d,e";
var myarray = mystring.split(",");
What I have in mind is a little more complicated. I have this dictionary-esque string:
myvalue=0;othervalue=1;anothervalue=0;
How do I split this so that the keys end up in one array and the values end up in another array?
Something like this:
var str = "myvalue=0;othervalue=1;anothervalue=0;"
var keys = [], values = [];
str.replace(/([^=;]+)=([^;]*)/g, function (str, key, value) {
keys.push(key);
values.push(value);
});
// keys contains ["myvalue", "othervalue", "anothervalue"]
// values contains ["0", "1", "0"]
Give a look to this article:
Search and Don't Replace
I'd still use string split, then write a method that takes in a string of the form "variable=value" and splits that on '=', returning a Map with the pair.
Split twice. First split on ';' to get an array of key value pairs. Then you could use split again on '=' for each of the key value pairs to get the key and the value separately.
You just need to split by ';' and loop through and split by '='.
var keys = new Array();
var values = new Array();
var str = 'myvalue=0;othervalue=1;anothervalue=0;';
var items = str.split(';');
for(var i=0;i<items.length;i++){
var spl = items[i].split('=');
keys.push(spl[0]);
values.push(spl[1]);
}
You need to account for that trailing ';' though at the end of the string. You will have an empty item at the end of that first array every time.

Categories

Resources