How to combine these two JavaScript arrays - javascript

I have two JavaScript arrays below that both have the same number of entries, but that number can vary.
[{"branchids":"5006"},{"branchids":"5007"},{"branchids":"5009"}]
[{"branchnames":"GrooveToyota"},{"branchnames":"GrooveSubaru"},{"branchnames":"GrooveFord"}]
I want to combine these two arrays so that I get
[{"5006":"GrooveToyota"},{"5007":"GrooveSubaru"},{"5008":"GrooveFord"}]
I'm not sure how to put it into words but hopefully someone understands. I would like to do this with two arrays of arbitrary length (both the same length though).
Any tips appreciated.

It's kind of a zip:
function zip(a, b) {
var len = Math.min(a.length, b.length),
zipped = [],
i, obj;
for (i = 0; i < len; i++) {
obj= {};
obj[a[i].branchids] = b[i].branchnames;
zipped.push(obj);
}
return zipped;
}
Example (uses console.log ie users)

var ids = [{"branchids":"5006"},{"branchids":"5007"},{"branchids":"5009"}];
var names = [{"branchnames":"GrooveToyota"},{"branchnames":"GrooveSubaru"},{"branchnames":"GrooveFord"}];
var combined = [];
for (var i = 0; i < ids.length; i++) {
var combinedObject = {};
combinedObject[ids[i].branchids] = names[i].branchnames;
combined.push(combinedObject);
}
combined; // [{"5006":"GrooveToyota"},{"5006":"GrooveSubaru"},{"5006":"GrooveFord"}]

Personally, I would do it IAbstractDownvoteFactor's way (+1), but for another option, I present the following for your coding pleasure:
var a = [{"branchids":"5006"},{"branchids":"5007"},{"branchids":"5009"}];
var b = [{"branchnames":"GrooveToyota"},{"branchnames":"GrooveSubaru"},{"branchnames":"GrooveFord"}];
var zipped = a.map(function(o,i){ var n={};n[o.branchids]=b[i].branchnames;return n;});

similar to #robert solution but using Array.prototype.map
var ids = [{"branchids":"5006"},{"branchids":"5007"},{"branchids":"5009"}],
names = [{"branchnames":"GrooveToyota"},{"branchnames":"GrooveSubaru"},{"branchnames":"GrooveFord"}],
merged = ids.map(function (o, i) { var obj = {}; obj[o.branchids]=names[i].branchnames; return obj; });
merged; //[{5006: "GrooveToyota"}, {5006: "GrooveSubaru"}, {5006:"GrooveFord"}]
Cheers!

Related

jQuery or JavaScript compare two arrays one contains an object

MyIds has just two Id numbers 1 and 2
var MyIds = [1,2]
but MyObject has three Id numbers 1, 2 and 3 (In reality this has about 500 Id's)
var MyObject = [{id:1,size:21,length:31},{id:2,size:22,length:32},{id:3,size:23,length:33}]
and I want to make a new variable that looks like this, I need some magic code that will compare the two variables and only return the details of the objects where the Is's match
var Result = [{id:1,size:21,length:31},{id:2,size:22,length:32}]
I'm happy to use jQuery if it help
Use Array.prototype.filter()
var Result = MyObject.filter(function(item){
return MyIds.indexOf(item.id) >-1;
});
It can be easily solved with underscore or lodash with something like:
Result = _.filter(MyObject, function (item) {
return _.indexOf(item.id, MyIds) !== -1;
});
I admit, this is a lazy answer. There is probably a way to make it without adding a news library. But lodash is so cool :)
It can be done without jQuery:
var MyIds = [1,2];
var MyObject = [{id:1,size:21,length:31},{id:2,size:22,length:32},{id:3,size:23,length:33}];
var Result = [];
MyObject.forEach(function(element) {
MyIds.forEach(function(id){
if(element.id == id)
Result.push(element);
});
});
A more diverse sollution without using any library:
function find(propName, filters, collection){
var temp = [];
for(var i = 0; i < collection.length; i++){
for(var j = 0; j < filters.length; j++){
if(collection[i][propName] === filters[j]){
temp.push(collection[i]);
break;
}
}
}
return temp;

Transform a string into an array of arrays in JavaScript

I'm searching the shortest method to transform a string like
"str1,str2,str3,..."
into an array of arrays like :
[["str1"], ["str2"], ["str3"]]
I could use a loop or an each, but I wonder if there is something more elegant.
You can make use of split() and map() like so:
// This could be turned into 1 line but is split here for readibility
var array = string.split(',');
array = array.map(function(value){
return [value];
});
Note: map() doesn't exist in all implementations, check out this article for more info on it.
If you are targeting an ES5 supporting browser you could use Array.map.
var array = "str1,str2,str3".split(",").map(function(token) {
return [token]
});
Tom Walter's answer is great, but in case you don't want to use map:
var str = "str1,str2,str3";
var arr = str.split(",");
var arrOfarrs = [];
for(var i = 0; i < arr.length; i++) {
arrOfarrs.push([arr[i]]);
}
Alternatively, you can add a map polyfill to add support for older browsers:
Array.prototype.map = Array.prototype.map || function(fn) {
var arr = [];
for(var i = 0; i < this.length; i++) {
arr.push(fn(this[i]));
}
return arr;
};
which would then allow you to do
var arr = str.split(",").map(function(val) {
return [val];
});

Finding an Object's value from an Array

Is there a simpler (or more efficient) way of achieving the following:
var _dataObjects = [{id:0, data:"data0", nextID:1},
{id:1, data:"data1", nextID:2},
{id:2, data:"data2", nextID:3} .. etc.];
generateNextPieceOfData();
function generateNextPieceOfData(){
var len = _dataObjects.length;
for ( var i = 0; i < len; i ++ ) {
var nextDataID = _dataObjects[i].nextID;
var nextData;
for ( var j = 0; j < len; j ++ ) {
if( _dataObjects[j].id == nextDataID ){
nextData = _dataObjects[j].data;
break;
}
}
}
}
The above example is abstracted from the problem I'm having and I realise the ID numbers are sequential in this instance but in the real problem nextID numbers do not run sequentially.
Thanks in advance.
Use the right data structure for your problem. Since you want to find an object by ID, create a hash map with the IDs as keys and objects as values:
var object_map = {};
for(var i = 0, l = _dataObjects.length; i < l; i++) {
objects[_dataObjects[i].id] = _dataObjects[i];
}
Then getting the next object is simply:
var next_object = object_map[someObject.nextID];
You still have iterate until some terminal condition is met though. For example:
function generatePath(id_a, id_b) {
var obj = object_map[id_a];
var path = [obj];
while (obj && obj.id !== id_b) {
obj = object_map[obj.nextID];
path.push(obj);
}
return path;
}
If your code works sequentially only, then you can sort the items by id or whatever and your code should work right? Try this:
_dataObjects = _dataObjects.sort(function(a, b) {
return a.id > b.id;
});

Extract specific substring using javascript?

If I have the following string:
mickey mouse WITH friend:goofy WITH pet:pluto
What is the best way in javascript to take that string and extract out all the "key:value" pairs into some object variable? The colon is the separator. Though I may or may not be able to guarantee the WITH will be there.
var array = str.match(/\w+\:\w+/g);
Then split each item in array using ":", to get the key value pairs.
Here is the code:
function getObject(str) {
var ar = str.match(/\w+\:\w+/g);
var outObj = {};
for (var i=0; i < ar.length; i++) {
var item = ar[i];
var s = item.split(":");
outObj[s[0]] = s[1];
}
return outObj;
}
myString.split(/\s+/).reduce(function(map, str) {
var parts = str.split(":");
if (parts.length > 1)
map[parts.shift()] = parts.join(":");
return map;
}, {});
Maybe something like
"mickey WITH friend:goofy WITH pet:pluto".split(":")
it will return the array, then Looping over the array.
The string pattern has to be consistent in one or the other way atleast.
Use split function of javascript and split by the word that occurs in common(our say space Atleast)
Then you need to split each of those by using : as key, and get the required values into an object.
Hope that's what you were long for.
You can do it this way for example:
var myString = "mickey WITH friend:goofy WITH pet:pluto";
function someName(str, separator) {
var arr = str.split(" "),
arr2 = [],
obj = {};
for(var i = 0, ilen = arr.length; i < ilen; i++) {
if ( arr[i].indexOf(separator) !== -1 ) {
arr2 = arr[i].split(separator);
obj[arr2[0]] = arr2[1];
}
}
return obj;
}
var x = someName(myString, ":");
console.log(x);

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