Output strings to arrays and output items from array - javascript

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]);
}

Related

How to enter a string to an array to a given position?

The condition is such that I have to enter a string to an array to a given position
such that all the pre position if not exist should be made to be empty strings.
example;
var array = []; // now I want to enter a string 'hello' at index 2
now the array should look like:
array = [ '','','hello']; //now lets say I want to enter a string 'world' at index 4
so the array should become:
array = [ '','','hello','','world'];
Is there a way to do this?
or do i have a better option to enter a string and and its position?
Please enlighten me.. :)
Something like this should do the trick. The function takes three arguments: the target array, the index (0-based) and the value. Just iterate from the finish of you array to the new position and add "" to each entry, then, after the loop, enqueue the desired string. Here's the fiddle.
let a = ['', '', 'Hello'];
function addStringAtPosition(
array,
key,
value
) {
for (let i = array.length; i < key; i++) {
array[i] = '';
}
array[key] = value;
}
addStringAtPosition(a, 5, 'World!');
First find out how many additional elements need to add ''
push these new elements to array.
push the required value at end.
PS: Assumed the index always higher than the array length. We can add conditions to cover those cases as well.
const insert = (arr, value, index) => {
arr.push(...new Array(index - arr.length).fill(""));
arr.push(value);
return arr;
};
const array = [];
insert(array, "hello", 2);
console.log(array);
insert(array, "world", 4);
console.log(array);

String into multiple string in an array

I have not been coding for long and ran into my first issue I just can not seem to figure out.
I have a string "XX|Y1234$ZT|QW4567" I need to remove both $ and | and push it into an array like this ['XX', 'Y1234', 'ZT', 'QW4567'].
I have tried using .replace and .split in every way I could like of
var array = "XX|Y1234$ZT|QW4567"
var array2 = [];
array = array.split("$");
for(i = o; i <array.length; i++)
var loopedArray = array[i].split("|")
loopedArray.push(array2);
}
I have tried several other things but would take me awhile to put them all down.
You can pass Regex into .split(). https://regexr.com/ is a great tool for messing with Regex.
// Below line returns this array ["XX", "Y1234", "ZT", "QW4567"]
// Splits by $ and |
"XX|Y1234$ZT|QW4567".split(/\$|\|/g);
Your code snippet is close, but you've messed up your variables in the push statement.
var array = "XX|Y1234$ZT|QW4567"
var array2 = [];
array = array.split("$");
for (i = 0; i < array.length; i++) {
var loopedArray = array[i].split("|")
array2.push(loopedArray);
}
array2 = array2.flat();
console.log(array2);
However, this can be rewritten much cleaner using flatMap. Also note the use of let instead of var and single quotes ' instead of double quotes ".
let array = 'XX|Y1234$ZT|QW4567'
let array2 = array
.split('$')
.flatMap(arrayI => arrayI.split('|'));
console.log(array2);
And lastly, split already supports multiple delimiters when using regex:
let array = 'XX|Y1234$ZT|QW4567'
let array2 = array.split(/[$|]/);
console.log(array2);
You can do this as follows:
"XX|Y1234$ZT|QW4567".replace('$','|').split('|')
It will produce the output of:
["XX", "Y1234", "ZT", "QW4567"]
If you call the split with two parameters | and the $ you will get an strong array which is splittend by the given characters.
var array = "XX|Y1234$ZT|QW4567";
var splittedStrings = array.Split('|','$');
foreach(var singelString in splittedStrings){
Console.WriteLine(singleString);
}
the output is:
XX
Y1234
ZT
QW4567

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

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]];

Javascript putting values in two-dimensional array

Is there a better way to create a two-dimensional array in javascript than this?
var divcookies = new Array();
divcookies[0] = new Array(2);
divcookies[0][0] = name;
divcookies[0][1] = value;
This results in a two dimensional array with bad data added in the middle of it. I expect an array like this.
(name1, value1, name2, value2, name3, value3)
Instead I get this.
(name1, value2, ,name2, value2, name3, value3)
I don't really know when that extra bad data is added because if I alert during the loop that fills the array it only seems to loop through 3 times to put the three pairs of values expected.
So I am looking for a different way to get the two dimensional array.
function get_cookies_array() {
var divcookies = new Array();
if (document.cookie && document.cookie != '') {
var split = document.cookie.split(';');
for (var i = 0; i < split.length; i++) {
var name_value = split[i].split("=");
name_value[0] = name_value[0].replace(/^ /, '');
if ( name_value[0].search("compage") != -1 ) {
alert (divname+" "+ divarray);
divcookies[i] = new Array(2);
divcookies[i][0] = decodeURIComponent(name_value[0]);
divcookies[i][1] = decodeURIComponent(name_value[1]);
}
}
}
alert (divcookies);
return divcookies;
}
jsBin http://jsbin.com/iwuqab
The recommended method for creating arrays in JS is to NOT use the 'new' method. Instead, do:
var divcookies = [];
divcookies[0] = [];
divcookies[0][0] = name;
divcookies[0][1] = value;
This notation frees you up from having to specify element numbers in advance. Once a variable's been initialized as an array, you can set any index you want. The downside (regardless of which notation you use) is that you have to initialize every sub-array as well.
Your 2-dimensional array is set up correctly (well, [] is preferred instead of new Array()). The actual problem is only with the display of your array using alert(divcookies). Here, divcookies is converted to a string using the predefined method toString(). This method creates a list of comma-separated array elements, from the first element to the last element. If some elements in between are not set, an empty string is output. In your case, you are not assigning to those indexes i of divcookies for which name_value[0].search("compage") == -1. These are the gaps ,, in the alerted list.

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