How to make array with string list - javascript

I have a generated list which is like this
196-1526, 85-651, 197-1519
I need the array like this. Each node has two part. I need only the first part of each node in one array.
196, 85, 197
I already have this code which generage 196
str.substr(0,str.indexOf('-'));

You could use the following:
'196-1526, 85-651, 197-1519'.replace(/-\d+(,|$)/g, '').split(/\s/)

If the input is a string you can use split() and push(), similar to this:
var x = "196-1526, 85-651, 197-1519"
var y = x.split(',');
var myArray = [];
for(i = 0; i < y.length; i++){
myArray.push(y[i].split('-')[0].trim());
}
DEMO - Using split() and push()

if it's an array
var myarray = ["196-1526", "85-651", "197-1519"];
var newarray = [];
var i = 0;
for(i = 0; i < myarray.length; i++){
var mnode = myarray[i].split("-");
newarray.push(mnode[0].trim());
}
and if it's a string
var myarray = "196-1526, 85-651, 197-1519".split(",");
var newarray = [];
var i = 0;
for(i = 0; i < myarray.length; i++){
var mnode = myarray[i].split("-");
newarray.push(mnode[0].trim());
}
Demo: http://jsfiddle.net/Dbbc8/

try this code using split
var text='196-1526, 85-651, 197-1519';
var splittedtext=text.split(',');
var numbers=new Array();
for(var i=0;i<splittedtext.length;i++)
{
var furthsplit=splittedtext[i].split('-');
numbers[i]=furthsplit[0];
}
alert(numbers);

var pairs = str.split(", ");
var values = [];
for (var i=0; i< pairs.length; i++) {
values.push(pairs[i].substr(0, pairs[i].indexOf('-')));
}

Related

Array in php with javascript

I have code like this:
$data = array();
for(int $i = 0; $i < 10; $i ++)
$data[$i][] = 5;
I don't know what's name of $data[$i][] = 5; in php and how to write this code in javascript?
or other hands, how can I write code above in javascript?
Thanks
P/s:
I want to write that code on nodeJs
You can try Array#push to add a element for array
var data = [];
for(var i = 0; i < 10; i ++)
if(!data[i]) data[i] = [];
data[i].push(5);
in this case, can understand $data[$i][] = 5; as below
$data[$i] = array();
array_push($data[$i],5);
// ex: [ 0 => [0 => 5]]
in Javascipt:
var data = [];
for (var i = 0; i < 10; i ++){
data[i] = [];
data[i].push(5);
}
Array.push() is a function used to insert a value into an array. But you can also use the C like way data[i] = 'value'.
data = [];
for (var i = 0; i < 10; i++)
data.push([5]);
document.write(JSON.stringify(data))
As an alternative use
data = [];
for(var i = 0; i < 10; i ++)
data[i] = [5];
document.write(JSON.stringify(data));
Use array.push() to add an item to the end of the array.
var sample = new Array();
sample.push(new Object());
To do this n times use a for loop.
var n = 100;
var sample = new Array();
for (var i = 0; i < n; i++)
sample.push(new Object());
Note that you can also substitute new Array() with [] and new Object() with {} so it becomes:
var n = 100;
var sample = [];
for (var i = 0; i < n; i++)
sample.push({});
JavaScript code:
var data = [];
for (i = 0; i < 10; i++) {
data[i] = [];
data[i][data[i].length] = 5;
}

javascript for loop using variable

Can I use variable to do the second for loop so it list out all data in GroupA1 and GroupB1.
Tried but fail.. anyone have idea how to make it work?
for example
function Loop(){
var AllGroup=["GroupA1","GroupB1"]
var GroupA1=["A1","A2"]
var GroupB1=["B1","B2"]
var Group=""
for(var i = 0; i < AllGroup.length; i++){
Group=AllGroup[i]
var SubGroup=""
for(var x = 0; x < Group.length; x++){
SubGroup=Group[x]
alert(SubGroup);
}
}
}
Hopefully my sample code can help you to deal with your question
For example
<script>
var GroupA1=["A1","A2"]
var GroupB1=["B1","B2"]
var Group=""
var AllGroup = [GroupA1, GroupB1]
for(var i = 0; i < AllGroup.length; i++){
Group=AllGroup[i]
var SubGroup=""
for(var x = 0; x < Group.length; x++){
SubGroup=Group[x]
alert(SubGroup);
}
}
</script>
Do it this way:
function loop(){
var GroupA1=["A1","A2"]
var GroupB1=["B1","B2"]
var AllGroup=[GroupA1,GroupB1]
var Group=""
for(var i = 0; i < AllGroup.length; i++){
Group=AllGroup[i]
var SubGroup=""
for(var x = 0; x < Group.length; x++){
SubGroup=Group[x]
alert(SubGroup);
}
}
}
Declare the arrays first then use them as objects in the next array.
This is the structure I would recommend, which is more logical, instead of what you're using.
function Loop(){
//The object AllGroups contains all the other groups
var AllGroups = {
"GroupA1": ["A1","A2"],
"GroupB1": ["B1","B2"]
};
for(var group in AllGroups){
if(AllGroups.hasOwnProperty(group)){
//Access each group in AllGroups
for(var i = 0; i < AllGroups[group].length; i++){
console.log(AllGroups[group][i]); //A1, A2, B1, B2
}
}
}
}
Rearrange code like this so that AllGroup is a collection containing GroupA1 and GroupB1:
function Loop() {
var GroupA1=["A1", "A2"];
var GroupB1=["B1", "B2"];
var AllGroup=[GroupA1, GroupB1];
var Group = null;
for(var i = 0; i < AllGroup.length; i++){
Group = AllGroup[i];
var SubGroup = "";
for(var x = 0; x < Group.length; x++){
SubGroup = Group[x];
alert(SubGroup);
}
}
}
Before you were referencing the strings "GroupA1" "GroupB1" not the actual data contained in the subgroups that you create.

Javascript - JSON String to Array

This is driving me mad, I have a JSON string that looks like so:
[["OX", "139.38"], ["LE", "131.28"], ["SA", "105.45"]]
I want to convert this to an array so that I can I can take advantage of indexOf:
alert(myArray.indexOf("LE"));
I've tried to convert my JSON string to an array using JSON.parse(myJSON) and jQuery.parseJSON(myJSON) but neither work.
How can I create an array from my JSON string? I'm happy to set up a loop just not sure how.
This works in chrome console:
var s = '[["OX", "139.38"], ["LE", "131.28"], ["SA", "105.45"]]';
var a = JSON.parse(s);
// a = [["OX", "139.38"],["LE", "131.28"],["SA", "105.45"]]
If you want to create a data structure to lookup the values by the keys:
var dict = {};
for (var i=0; i<a.length; i++){
dict[a[i][0]] = a[i][1];
}
Now dict looks like this:
//dict = {OX:"139.38", LE:"131.28", SA:"105.45"}
and we can index into it with the keys
dict['LE'] // = "131.28"
This will convert it like this [[""OX", "139.38"], ["LE", "131.28""]] -> ["OX", "LE"]
var newArr = [];
for(var i = 0; i < myArr.length; i++) {
newArr.push(myArr[i][0]);
}
This will convert it like this [[""OX", "139.38"], ["LE", "131.28""]] -> ["OX", "139.38", "LE", "131.28"]
var newArr = [];
for(var i = 0; i < myArr.length; i++) {
var tempArr = myArr[i];
for(var j = 0; j < tempArr.length; j++) {
newArr.push(tempArr[j]);
}
}
Now you can use indexOf.
If you want to get index at outter array:
var x = '[["OX", "139.38"], ["LE", "131.28"], ["SA", "105.45"]]';
var y = JSON.parse(x);
function getIndexByKey(key,array){
for(var i=0, len = array.length; i<len;i++){
if(array[i][0] === key){
return i;
}
}
}
function getIndexByVal(val,array){
for(var i=0, len = array.length; i<len;i++){
if(array[i][1] === val){
return i;
}
}
}
calling it:
getIndexByKey('OX', y); //0
getIndexByKey('LE', y); // 1
getIndexByKey('SA', y) // 2
getIndexByVal('139.38', y); //0
...

Create arrays dynamically in a loop with javascript

Here's a pseudocode example about what I'm trying to do:
var totalLanguages = XX;
for(var i = 0; i < totalLanguages; i++){
var dynamicArray + i = new Array();
/*.....*/
}
I need to create dynamically many arrays as the value of totalLanguages which can be either number.
This is to be able to do something like this:
for(var i = 0; i < totalLanguages; i++){
var arrayLanguages["es"] = dynamicArray+i;
var arrayLanguages["en"] = dynamicArray+i;
}
Is there any way to do this?
var languageNames = ['en', 'es'];
var languages = {};
for (var i = 0; i < languageNames.length; i++) {
languages[languageNames[i]] = [];
}
You are basically trying to recreate an array with variable names. Just use an Array to start out!
var dynamicArray = [];
for(var i = 0; i < totalLanguages; i++) {
dynamicArray[i] = new Array();
}
You can use multi-dimensional arrays:
var languagesArray = new Array(totalLanguages);
for(var i = 0; i < totalLanguages; i++) {
var innerArray = new Array();
innerArray.push("Hello");
innerArray.push("World");
languagesArray[i] = innerArray;
}
console.log(languagesArray[0][0]);
See: How can I create a two dimensional array in JavaScript?
How about:
for(var i = 0; i < totalLanguages; i++){
window["dynamicvariable " + i] = new Array();
/*.....*/
}

Handling multidimentional array in java script is not working

function split(str)
{
var array = str.split(';');
var test[][] = new Array();
for(var i = 0; i < array.length; i++)
{
var arr = array[i].split(',');
for(var j = 0; j < arr.length; j++)
{
test[i][j]=arr[j];
}
}
}
onchange="split('1,2,3;4,5,6;7,8,9;a,b,c;d,e,f;g,h,i')"
it was not working. i need to split this string to 6*3 multi dimentional array
var array[][] = new Array() is not valid syntax for declaring arrays. Javascript arrays are one dimensional leaving you to nest them. Which means you need to insert a new array into each slot yourself before you can start appending to it.
Like this: http://jsfiddle.net/Squeegy/ShWGB/
function split(str) {
var lines = str.split(';');
var test = [];
for(var i = 0; i < lines.length; i++) {
if (typeof test[i] === 'undefined') {
test[i] = [];
}
var line = lines[i].split(',');
for(var j = 0; j < line.length; j++) {
test[i][j] = line[j];
}
}
return test;
}
console.log(split('a,b,c;d,e,f'));
var test[][] is an invalid javascript syntax.
To create a 2D array, which is an array of array, just declare your array and push arrays into it.
Something like this:
var myArr = new Array(10);
for (var i = 0; i < 10; i++) {
myArr[i] = new Array(20);
}
I'll let you apply this to your problem. Also, I don't like the name of your function, try to use something different from the standards, to avoid confusion when you read your code days or months from now.
function split(str)
{
var array = str.split(';'),
length = array.length;
for (var i = 0; i < length; i++) array[i] = array[i].split(',');
return array;
}
Here's the fiddle: http://jsfiddle.net/AbXNk/
var str='1,2,3;4,5,6;7,8,9;a,b,c;d,e,f;g,h,i';
var arr=str.split(";");
for(var i=0;i<arr.length;i++)arr[i]=arr[i].split(",");
Now arr is an array with 6 elements and each element contain array with 3 elements.
Accessing element:
alert(arr[4][2]); // letter "f" displayed

Categories

Resources