array spliting based on our requirement - javascript

My array contains the values with comma as separator, like
array={raju,rani,raghu,siva,stephen,varam}.
But i want to convert into the below format like
array = {raju:rani raghu:siva atephen:varam}.
please give some logic to implement this one.

If you're starting with a string, you can split it upon comma:
var myString = 'raju,rani,raghu,siva,stephen,varam';
var array = myString.split(',');
Given that, you can do the following:
var array = [ 'raju', 'rani', 'raghu', 'siva', 'stephen', 'varam' ];
var result = {};
for(var i = 0; i < array.length; i+= 2) {
result[array[i]] = array[i+1];
}
... which gives the answer you've requested.
Keep in mind that if the array is not evenly divisible by 2, the value of the last item will be undefined.

This is how to convert array to key-value pair of objects (odd-index is key, even-index is value in the resulting key-value pairs)
var array = ['raju', 'rani', 'raghu','siva','stephen','varam'],
pairs = {};
for (var i = 0; i < array.length; i += 2) {
pairs [array[i]] = array[i + 1];
}

Related

Javascript - nested loops and indexes

I am trying to build an array that should look like this :
[
[{"name":"Mercury","index":0}],
[{"name":"Mercury","index":1},{"name":"Venus","index":1}],
[{"name":"Mercury","index":2},{"name":"Venus","index":2},{"name":"Earth","index":2}],
...
]
Each element is the concatenation of the previous and a new object, and all the indexes get updated to the latest value (e.g. Mercury's index is 0, then 1, etc.).
I have tried to build this array using the following code :
var b = [];
var buffer = [];
var names = ["Mercury","Venus","Earth"]
for (k=0;k<3;k++){
// This array is necessary because with real data there are multiple elements for each k
var a = [{"name":names[k],"index":0}];
buffer = buffer.concat(a);
// This is where the index of all the elements currently in the
// buffer (should) get(s) updated to the current k
for (n=0;n<buffer.length;n++){
buffer[n].index = k;
}
// Add the buffer to the final array
b.push(buffer);
}
console.log(b);
The final array (b) printed out to the console has the right number of objects in each element, but all the indexes everywhere are equal to the last value of k (2).
I don't understand why this is happening, and don't know how to fix it.
This is happening because every object in the inner array is actually the exact same object as the one stored in the previous outer array's entries - you're only storing references to the object, not copies. When you update the index in the object you're updating it everywhere.
To resolve this, you need to create new objects in each inner iteration, or use an object copying function such as ES6's Object.assign, jQuery's $.extend or Underscore's _.clone.
Here's a version that uses the first approach, and also uses two nested .map calls to produce both the inner (variable length) arrays and the outer array:
var names = ["Mercury","Venus","Earth"];
var b = names.map(function(_, index, a) {
return a.slice(0, index + 1).map(function(name) {
return {name: name, index: index};
});
});
or in ES6:
var names = ["Mercury","Venus","Earth"];
var b = names.map((_, index, a) => a.slice(0, index + 1).map(name => ({name, index})));
Try this:
var names = ["Mercury","Venus","Earth"];
var result = [];
for (var i=0; i<names.length; i++){
var _temp = [];
for(var j=0; j<=i; j++){
_temp.push({
name: names[j],
index:i
});
}
result.push(_temp);
}
console.log(result)
try this simple script:
var b = [];
var names = ["Mercury","Venus","Earth"];
for(var pos = 0; pos < names.length; pos++) {
var current = [];
for(var x = 0; x < pos+1; x++) {
current.push({"name": names[x], "index": pos});
}
b.push(current);
}

Comma Delimiter Multi Dimensional Array

I have an array (call it array[]), with elements of the following format separated by a comma:
array[0] = abc, def, 123, ghi
How can I pass this into another multi-dimensional array (lets say arrayTwo[]) such that arrayTwo is as follows:
arrayTwo[0][0] = "abc"
arrayTwo[0][1] = "def"
arrayTwo[0][2] = "123"
arrayTwo[0][3] = "ghi"
I am really unsure about the comma as a delimiter portion (use split()?). I believe the looping part should not be too difficult for me to handle. Thanks for any help!
You can split the items by ,\s* regex which is comma followed by zero or more spaces. This will create an array. Then just insert that array into the appropriate element of arrayTwo.
arrayTwo = array.map(function (item) {
return item.split(/,\s*/)
});
Unrolled slightly it would look like:
arrayTwo = [];
for (var x = 0; x < array.length; x++) {
var item = array[x].split(/,\s*/);
arrayTwo[x] = [];
for (var i = 0; i < item.length; i++) {
arrayTwo[x][i] = item[i];
}
}

slice string to pieces and store each in new array

Help needed.
I have string like ["wt=WLw","V5=9jCs","7W=71X","rZ=HRP9"] (unlimited number of pairs)
I need to make an array with pair like wT (as index) and WLw as value, for the whole string (or simpler wT as index0, WLw as index 1 and so on)
I'm trying to do it in JavaScript but I just cant figure out how to accomplish this task.
Much much appreciate your help!!
You cannot have a string as an index in an array, what you want is an object.
All you need to do is loop over your array, split each value into 2 items (key and value) then add them to an object.
Example:
// output is an object
var output = {};
var source = ["wt=WLw","V5=9jCs","7W=71X","rZ=HRP9"];
for (var index = 0; index < source.length; index++) {
var kvpair = source[index].split("=");
output[kvpair[0]] = kvpair[1];
}
If you wanted an array of arrays, then its much the same process, just pushing each pair to the output object
// output is a multidimensional array
var output = [];
var source = ["wt=WLw","V5=9jCs","7W=71X","rZ=HRP9"];
for (var index = 0; index < source.length; index++) {
output.push(source[index].split("="));
}
Update If your source is actually a string and not an array then you will have to do a little more splitting to get it to work
var output = {};
var sourceText = "[\"wt=WLw\",\"V5=9jCs\",\"7W=71X\",\"rZ=HRP9\"]";
// i have escaped the quotes in the above line purely to make my example work!
var source = sourceText.replace(/[\[\]]/g,"").split(",");
for (var index = 0; index < source.length; index++) {
var kvpair = source[index].split("=");
output[kvpair[0]] = kvpair[1];
}
Update 2
If your desired output is an array of arrays instead of an object containing key-value pairs then you will need to do something like #limelights answer.
Object with Key-Value pairs: var myObject = { "key1": "value1", "key2": "value2" };
with the above code you can access "value1" like this myObject["key1"] or myObject.key1
Array of Arrays: var myArray = [ [ "key1", "value1"] ,[ "key2", "value2" ] ];
with this code, you cannot access the data by "key" (without looping through the whole lot to find it first). in this form both "key1" and "value1" are actually values.
to get "value1" you would do myArray[0][1] or you could use an intermediary array to access the pair:
var pair = myArray[0];
> pair == ["key1", "value1"]
> pair[0] == "key1"
> pair[1] == "value1"
You can use a for each loop on both types of result
// array of arrays
var data = [ [ "hello", "world"], ["goodbye", "world"]];
data.forEach(function(item) {
console.log(item[0]+" "+item[1]);
});
> Hello World
> Goodbye World
// object (this one might not work very well though)
var data = { "hello": "world", "goodbye": "world" };
Object.keys(data).forEach(function(key) {
console.log(key+" "+data[key]);
});
> Hello World
> Goodbye World
The normal for loop would do perfectly here!
var list = ["wt=WLw","V5=9jCs","7W=71X","rZ=HRP9"];
var pairs = [];
for(var i = 0; i < list.length; i++){
pairs.push(list[i].split('='));
}
This would give you an array of pairs, which I assume you want.
Otherwise just get rid of the outer Array and do list[i].split('=');
If you want it put into an object ie. not an Array
var pairObject = {};
for(var i = 0; i < list.length; i++){
var pair = list[i].split('=');
pairObject[pair[0]] = pair[1];
}

JavaScript: convert objects to array of objects

I have thousands of legacy code that stores array information in a non array.
For example:
container.object1 = someobject;
container.object2 = someotherobject;
container.object3 = anotherone;
What I want to have is:
container.objects[1], container.objects[2], container.objects[3] etc.
The 'object' part of the name is constant. The number part is the position it should be in the array.
How do I do this?
Assuming that object1, object2, etc... are sequential (like an array), then you can just iterate through the container object and find all the sequential objectN properties that exist and add them to an array and stop the loop when one is missing.
container.objects = []; // init empty array
var i = 1;
while (container["object" + i]) {
container.objects.push(container["object" + i]);
i++;
}
If you want the first item object1 to be in the [1] spot instead of the more typical [0] spot in the array, then you need to put an empty object into the array's zeroth slot to start with since your example doesn't have an object0 item.
container.objects = [{}]; // init array with first item empty as an empty object
var i = 1;
while (container["object" + i]) {
container.objects.push(container["object" + i]);
i++;
}
An alternate way to do this is by using keys.
var unsorted = objectwithobjects;
var keys = Object.keys(unsorted);
var items = [];
for (var j=0; j < keys.length; j++) {
items[j] = unsorted[keys[j]];
}
You can add an if-statement to check if a key contains 'object' and only add an element to your entry in that case (if 'objectwithobjects' contains other keys you don't want).
That is pretty easy:
var c = { objects: [] };
for (var o in container) {
var n = o.match(/^object(\d+)$/);
if (n) c.objects[n[1]] = container[o];
}
Now c is your new container object, where c.object[1] == container.object1

Reorganize array of arrays to array of hashes and convert to JSON

I have the following array
var arr=[[10,20,30],[12,21,33],[13,23,35]];
How can I convert that array to JSON.
Desired result
myJSONarr=[
{"x":10 ,"y":20,"z":30},
{"x":12 ,"y":21,"z":33},
{"x":13, "y":23,"z":35}
];
I'm guessing I will have to define sting array
var objArray=["x","y","z"];
and do loop over these two values with the eval() function.
Any help is greatly appreciated.
if you use jquery:
var arr=[[10,20,30],[12,21,33],[13,23,35]],
myjson = JSON.stringify($.map(arr,function(a){return {x:a[0],y:a[1],z:a[2]}}));
http://jsfiddle.net/herostwist/yDRwh/
if you use prototype:
var myjson = JSON.stringify([[10,20,30],[12,21,33],[13,23,35]].map(function(a){
return {x:a[0],y:a[1],z:a[2]}}));
http://jsfiddle.net/herostwist/yDRwh/1/
My version. Edit: I didn't twig objArray wasn't part of the problem, but the OP's suggestion as part of the solution. Oh well, I like it anyway.
var arr=[[10,20,30],[12,21,33],[13,23,35]];
var objArray=["x","y","z"];
var myJSONarr = [];
for (var idx = 0; idx != arr.length; idx++) {
var row = {};
for (var idx2 = 0; idx2 != objArray.length; idx2++) {
row[objArray[idx2]] = arr[idx][idx2];
}
myJSONarr.push(row);
}
alert(JSON.stringify(myJSONarr));
Many different answers, here's another:
http://jsfiddle.net/Vecqc/
<textarea id="text" style="width: 100%;"></textarea>
var arr = [[10,20,30],[12,21,33],[13,23,35]];
var stringify = [];
for (var i = 0; i < arr.length; i++) {
stringify[i] = {'x':arr[i][0],'y':arr[i][0],'z':arr[i][0]};
}
document.getElementById('text').value = JSON.stringify(stringify);
Assuming you just want to map the values to JavaScript objects†:
var objs = [];
for(var i = 0, l = arr.length; i < l; i++) {
var p = arr[i];
objs.push({x: p[0], y: p[1], z: p[2]});
}
If you really want to create a JSON string, then you can pass this array to JSON.stringify. JSON is available in all modern browser and can be loaded for older ones.
†: Why am I assuming here? Because people confuse JSON with JavaScript object literals. In your code, myJSONarr is not JSON. It is an array of JS objects. It would be JSON if the data would be contained in a string:
var myJSONarr = '[{"x":10, "y":20, "z":30}, ...]';
JSON != JavaScript object
What you are describing is not merely a JSON conversion. You actually have an array full of three element arrays of numbers, and what you are wanting is JSON for an array of hashes where each triplet becomes a hash over "x","y","z".
Anyway, if you want a simple .toJSON() function, Prototype.js includes a .toJSON() function onto most objects that makes it really easy.
http://www.prototypejs.org/learn/json
Untested...
var arr=[[10,20,30],[12,21,33],[13,23,35]];
var myarrOfXYZ = arr.collect(function(T){ return $H({ x: T[0], y: T[1], z: T[2] }) });
var myJSON = myarrOfXYZ.toJSON();
Note that prototype also provides a function "zip" that can be used on line 2 instead of $H
Just loop through the array and create a string from each array inside it, then join the strings to form the JSON string:
var items = [];
for (var i = 0; i < arr.length; i++) {
items.push('{"x":'+arr[i][0]+',"y":'+arr[i][1]+',"z":'+arr[i][2]+'}');
}
var myJSONarr = '[' + items.join(',') + ']';
First:
var arr = [[10,20,30], [12,21,33], [13,23,35]];
var arr2 = [];
for (var i in arr) {
var a = arr[i];
arr2.push({
x: a[0],
y: a[1],
z: a[2]
});
}
Or, using higher-order functions:
var labels = ["x", "y", "z"];
var arr = [[10,20,30], [12,21,33], [13,23,35]];
var arr2 = arr.map(function(a) {
return a.reduce(function(prev, curr, i) {
prev[labels[i]] = curr;
return prev;
}, {});
});
Then directly convert the new array to JSON.

Categories

Resources