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
...
Related
Hi I'm trying to split a string based on multiple delimiters.Below is the code
var data="- This, a sample string.";
var delimiters=[" ",".","-",","];
var myArray = new Array();
for(var i=0;i<delimiters.length;i++)
{
if(myArray == ''){
myArray = data.split(delimiters[i])
}
else
{
for(var j=0;j<myArray.length;j++){
var tempArray = myArray[j].split(delimiters[i]);
if(tempArray.length != 1){
myArray.splice(j,1);
var myArray = myArray.concat(tempArray);
}
}
}
}
console.log("info","String split using delimiters is - "+ myArray);
Below is the output that i get
a,sample,string,,,,This,
The output that i should get is
This
a
sample
string
I'm stuck here dont know where i am going wrong.Any help will be much appreciated.
You could pass a regexp into data.split() as described here.
I'm not great with regexp but in this case something like this would work:
var tempArr = [];
myArray = data.split(/,|-| |\./);
for (var i = 0; i < myArray.length; i++) {
if (myArray[i] !== "") {
tempArr.push(myArray[i]);
}
}
myArray = tempArr;
console.log(myArray);
I'm sure there's probably a way to discard empty strings from the array in the regexp without needing a loop but I don't know it - hopefully a helpful start though.
Here you go:
var data = ["- This, a sample string."];
var delimiters=[" ",".","-",","];
for (var i=0; i < delimiters.length; i++) {
var tmpArr = [];
for (var j = 0; j < data.length; j++) {
var parts = data[j].split(delimiters[i]);
for (var k = 0; k < parts.length; k++) {
if (parts[k]) {
tmpArr.push(parts[k]);
}
};
}
data = tmpArr;
}
console.log("info","String split using delimiters is - ", data);
Check for string length > 0 before doing a concat , and not != 1.
Zero length strings are getting appended to your array.
I have a Javascript array with multiple arrays inside. I was trying to loop through the array to return an aggregated array. So far I have done following with no luck:
var a = [[1,2,3],[4,5,56],[2,5,7]];
var x = [];
for ( var i = 0; i < a.length; i++) {
for ( var j = 0; j < a[i].length; j++) {
console.log(a[i][i] = a[i][j]+a[j][i]);
}
}
I am trying to obtain the following result:
console.log(a); // -> [7,12,66]
Any suggestions or pin points where I can look for examples of similar things would be appreciated.
assuming the elements of a has the same length, the following should work
var x=[];
for(var i=0; i<a[0].length; i++){
var s = 0;
for(var j=0; j<a.length; j++){
s += a[j][i];
}
x.push(s);
}
a[0].map(function(b,i){return a.reduce(function(c,d){return c+d[i];},0);})
// [7, 12, 66]
From dc2 to dc1, try this:
var a = [[1,2,3],[4,5,56],[2,5,7]];
var x = [];
for ( var i =0; i < a.length; i++){
for ( var j = 0; j < a[i].length; j++){
x[j] = x[j] || 0;
x[j] = x[j] + a[i][j];
}
}
This worked in testing, and doesn't error with different array lengths.
Hey i have a simple question i cant find an answer,
i´m trying to generate some raw-data for a chart
lets say i have an array like :
[1,0,0,1,2,0]
is there a way to make an array out of it that has nested arrays that represent the count of duplicate entrys ?
[[0,3],[1,2],[2,1]]
here is some code that does the trick, but saves the count as objects
var array = [1,0,0,1,2,0];
var length = array.length;
var objectCounter = {};
for (i = 0; i < length; i++) {
var currentMemboerOfArrayKey = JSON.stringify(array[i]);
var currentMemboerOfArrayValue = array[i];
if (objectCounter[currentMemboerOfArrayKey] === undefined){
objectCounter[currentMemboerOfArrayKey] = 1;
}else{
objectCounter[currentMemboerOfArrayKey]++;
}
}
but objectCounter returns them like
{0:3,1:2,2:1}
but i need it as an array i specified above ?
for any help, thanks in advance
Try
var array = [1, 0, 0, 1, 2, 0];
function counter(array) {
var counter = [],
map = {}, length = array.length;
$.each(array, function (i, val) {
var arr = map[val];
if (!arr) {
map[val] = arr = [val, 0];
counter.push(arr);
}
arr[1] += 1;
})
return counter;
}
console.log(JSON.stringify(counter(array)))
Demo: Fiddle
You can turn your object into an array easily:
var obj = {0:3,1:2,2:1};
var arr = [];
for (var key in obj) {
// optional check against Object.prototype changes
if (obj.hasOwnProperty(key)) {
arr.push([+key, obj[key]]);
}
}
Note: The object keys are strings, so i converted them back to numbers when placed in the array.
Functional way of doing this, with Array.reduce and Array.map
var data = [1,0,0,1,2,0];
var result = data.reduce(function(counts, current) {
counts[current] = current in counts ? counts[current] + 1: 1;
return counts;
}, {});
result = Object.keys(result).map(function(current){
return [parseInt(current), result[current]];
});
console.log(result);
Output
[ [ 0, 3 ], [ 1, 2 ], [ 2, 1 ] ]
Try:
var data = [1,0,0,1,2,0];
var len = data.length;
var ndata = [];
for(var i=0;i<len;i++){
var count = 0;
for(var j=i+1;j<len;j++){
if(data[i] == data[i]){
count ++;
}
}
var a = [];
a.push(data[i]);
a.push(count);
ndata.push(a);
}
console.log(ndata)
DEMO here.
First you need to map the array to an associative object
var arr = [1,0,0,1,2,0];
var obj = {};
for (var i = 0; i < arr.length; i++) {
if (obj[arr[i]] == undefined) {
obj[arr[i]] = 0;
}
obj[arr[i]] += 1;
}
Then you can easily turn that object into a 2d matrix like so:
arr = [];
for (var k in obj) {
arr.push([k, obj[k]]);
}
alert(JSON.stringify(arr));
Your existing object can be turned into an array with a simple for..in loop. Also your existing code that produces that object can be simplified. Encapsulate both parts in a function and you get something like this:
function countArrayValues(array) {
var counter = {},
result = [];
for (var i = 0, len = array.length; i < len; i++)
if (array[i] in counter)
counter[array[i]]++;
else
counter[array[i]] = 1;
for (i in counter)
result.push([+i, counter[i]]);
return result;
}
console.log( countArrayValues([1,0,0,1,2,0]) );
Demo: http://jsfiddle.net/hxRz2/
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('-')));
}
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