D3 - How to merge 2 arrays based on their row index - javascript

I am working on visualization using D3 and need to merge 2 arrays based on row index:
var links =
[
{"source":"a0","target":"a0","s_portfolio":"a","t_portfolio":"a","SOURCE_TYPE":"APP","DES_TYPE":"APP"},
{"source":"a1","target":"a2","s_portfolio":"a","t_portfolio":"c","SOURCE_TYPE":"APP","DES_TYPE":"APP"},
{"source":"a1","target":"a2","s_portfolio":"a","t_portfolio":"c","SOURCE_TYPE":"APP","DES_TYPE":"APP"}
];
var files =
[
{"File_Desc":"","DataName":""},
{"File_Desc":"Date","DataName":"Dates.01012016"},
{"File_Desc":"Address","DataName":"Address.01012016"}
];
To get:
var result =
[
{"source":"a0","target":"a0","s_portfolio":"a","t_portfolio":"a","SOURCE_TYPE":"APP","DES_TYPE":"APP","File_Desc":"","DataName":""},
{"source":"a1","target":"a2","s_portfolio":"a","t_portfolio":"c","SOURCE_TYPE":"APP","DES_TYPE":"APP","File_Desc":"Date","DataName":"Dates.01012016"},
{"source":"a1","target":"a2","s_portfolio":"a","t_portfolio":"c","SOURCE_TYPE":"APP","DES_TYPE":"APP","File_Desc":"Address","DataName":"Address.01012016"}
]

If you can use late model JavaScript (aka ES2015),
the shortest path is something like:
var result = links.map((d,i) => Object.assign({}, d, files[i]));
This is short. It also doesn't modify either links or files (should you wish to use them stand-alone separately from result).
P.S.
The comments suggest you're concerned about the runtime of the alternative solutions. In general, they're all okay, esp. as the kind of one-time data setup common in d3 apps. But, if you have large datasets or run record merges often, then you might want to optimize.
If you're willing to update one of your existing record sets rather than create a fresh new one:
links.forEach((d,i) => Object.assign(d, files[i]));
After this, links has the updated records. This runs 7-10x faster than the other solutions, presumably because it's not creating a ton of new objects. If you're done with the original, un-merged links or files objects, there's no particular reason to avoid this kind of "destructive" or "in place" update. There's often little need to optimize one-time setup operations. But if you wanted or needed to do so, this is a strong way.

Try this:
var links = [
{"source":"a0","target":"a0","s_portfolio":"a","t_portfolio":"a","SOURCE_TYPE":"APP","DES_TYPE":"APP"},
{"source":"a1","target":"a2","s_portfolio":"a","t_portfolio":"c","SOURCE_TYPE":"APP","DES_TYPE":"APP"},
{"source":"a1","target":"a2","s_portfolio":"a","t_portfolio":"c","SOURCE_TYPE":"APP","DES_TYPE":"APP"}
];
var files = [
{"File_Desc":"","DataName":""},
{"File_Desc":"Date","DataName":"Dates.01012016"},
{"File_Desc":"Address","DataName":"Address.01012016"}
];
var result = [];
for(let i = 0; i < links.length; i++){
result[i] = Object.assign(links[i], files[i]);
}
console.log(result);

I'd probably iterate over one array with an array map and then in my callback function return a combined object using a function such as the one defined in this answer.
var result = links.map(combineLinkToFile);
function combineLinkToFile (link, index) {
var file = files[index];
return collect(link, file)
}
function collect() {
var ret = {};
var len = arguments.length;
for (var i=0; i<len; i++) {
for (p in arguments[i]) {
if (arguments[i].hasOwnProperty(p)) {
ret[p] = arguments[i][p];
}
}
}
return ret;
}

Using jQuery map() and extend() methods:
function mergeObjectsInArrays(arr1, arr2){
return $.map(arr1, function(el, i){
return $.extend(el, arr2[i]);
});
};
// then pass your arrays:
var result = mergeObjectsInArrays(links, files);

Related

Array with key value string into Object JavaScript

I am looking for some help, I am working on a piece of code for a client, the client currently have their analytics tag hardcoded to the page with all the key values being sent.
We are in the process of converting them to a new analytics platform using a tag management system, they have been able to update the majority of their platforms to create an object that the new analytics platform can reference but as this site is managed by a 3rd party they are unable to get this resolved in time for our release.
I have managed to successfully pull the tag and split the tag in to parameters:
var x = $('img[alt="MI_TAG"]').attr("src");
x.split("&");
Which creates the array:
1:"109=jsp.searchFlights.initial"
2:"117=Flight Only Journey"
3:"206=02/11/2017"
4:"208=03/11/2017"
5:"212=ALL"
What I want to do is take these array strings to create an object call "mi", like so:
109:"jsp.searchFlights.initial"
117:"Flight Only Journey"
204:""
205:""
206:"02/11/2017"
208:"03/11/2017"
Can someone help?
Thanks all for your help, I have managed to take some of the advice here and create the object and see it logging out:
var x = $('img[alt="MI_TAG"]').attr("src");
var split = x.split("&");
var arrayLength = split.length;
var arr = [];
var i = 0;
do {
arr.push(split[i].replace('=',':'));
arr.toString();
console.log(arr);
i += 1;
} while (i < arrayLength);
let mi = {};
arr.forEach(item=>{
let tempArr = item.split(':');
mi[tempArr[0]] = tempArr[1];
})
console.log(mi);
The issue I now seem to be facing is scope, I want my object to be globally referenceable, how do I do that?
From your array, use reduce - split on the = sign in your string, and create the object:
let newObject = arr.reduce((obj, item) => {
let parts = item.split("=");
obj[parts[0]] = parts[1];
return obj;
}, {});
Assuming you are using at least ECMAScript 5.1 you could use Array.prototype.forEach() to iterate over your array and produce the object.
let myArray = ["109=jsp.searchFlights.initial", "117=Flight Only Journey", "206=02/11/2017", "208=03/11/2017",
"212=ALL"];
let myObject = {};
myArray.forEach(item=>{
let tempArr = item.split('=');
myObject[tempArr[0]] = tempArr[1];
})
console.log(myObject);
Produces:
{
"109": "jsp.searchFlights.initial",
"117": "Flight Only Journey",
"206": "02/11/2017",
"208": "03/11/2017",
"212": "ALL"
}

Sorting 2D javascript array

I have an array containing a list of tags and count.
tags_array[0] = tags;
tags_array[1] = tags_count;
I need to sort the arrays base on the count so that I can pick out the top few tags.
Sort one, while storing the sort comparisons. Then sort the other using those results:
var res = [];
tags_count.sort( function( a, b ){ return res.push( a=a-b ), a; } );
tags.sort( function(){ return res.shift(); } );
Supposing tags and tags_count are 2 arrays of same length, I would first build a proper array of objects :
var array = [];
for (var i=0; i<tags_count.length; i++) {
array.push({tag:tags[i], count:tags_count[i]});
}
And then sort on the count :
array.sort(function(a, b) {return a.count-b.count});
If you need to get your arrays back after that, you may do
for (var i=0; i<array.length; i++) {
tags[i] = array[i].tag;
tags_count[i] = array[i].count;
}
Demonstration
Assuming that both tags and tags_count are arrays with the same length (that part of the question wasn't too clear), the following is one way to do the trick.
var tags_array = new Array();
for (var i = 0; i < tags.length; i++)
{
tags_array[i] = {};
tags_array[i].tagName = tags[i];
tags_array[i].tagCount = tags_count[i];
}
tags_array.sort(function(a,b){return b.tagCount-a.tagCount});
One should note that it might be possible to structure the data in this way from the start instead of rewriting it like this, in which case that is preferable. Likewise, a better structure can be used to save the data, but this will work.

How to "clean" an array in javascript?

I am stuck here. How can I clean this array:
{"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]}
So that it looks like:
["5201521d42","52049e2591","52951699w4"]
I am using Javascript.
You just need to iterate over the existing data array and pull out each id value and put it into a new "clean" array like this:
var raw = {"data":[{"":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
var clean = [];
for (var i = 0, len = raw.data.length; i < len; i++) {
clean.push(raw.data[i].id);
}
Overwriting the same object
var o = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
for (var i = o.data.length; i--; ){
o.data[i] = o.data[i].id;
}
What you're doing is replacing the existing object with the value of its id property.
If you can use ES5 and performance is not critical, i would recommend this:
Edit:
Looking at this jsperf testcase, map vs manual for is about 7-10 times slower, which actually isn't that much considering that this is already in the area of millions of operations per second. So under the paradigma of avoiding prematurely optimizations, this is a lot cleaner and the way forward.
var dump = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
var ids = dump.data.map(function (v) { return v.id; });
Otherwise:
var data = dump.data;
var ids = [];
for (var i = 0; i < data.length; i++) {
ids.push(data[i].id);
}
Do something like:
var cleanedArray = [];
for(var i=0; i<data.length; i++) {
cleanedArray.push(data[i].id);
}
data = cleanedArray;
Take a look at this fiddle. I think this is what you're looking for
oldObj={"data":[{"":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
oldObj = oldObj.data;
myArray = [];
for (var key in oldObj) {
var obj = oldObj[key];
for (var prop in obj) {
myArray.push(obj[prop]);
}
}
console.log(myArray)
Use Array.prototype.map there is fallback code defined in this documentation page that will define the function if your user's browser is missing it.
var data = {"data":[{"":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
var clean_array = [];
for( var i in data.data )
{
for( var j in data.data[i] )
{
clean_array.push( data.data[i][j] )
}
}
console.log( clean_array );
You are actually reducing dimension. or you may say you are extracting a single dimension from the qube. you may even say selecting a column from an array of objects. But the term clean doesn't match with your problem.
var list = [];
var raw = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]};
for(var i=0; i < raw.data.length ; ++i){
list.push(raw.data[i].id);
}
Use the map function on your Array:
data.map(function(item) { return item.id; });
This will return:
["5201521d42", "52049e2591", "52951699w4"]
What is map? It's a method that creates a new array using the results of the provided function. Read all about it: map - MDN Docs
The simplest way to clean any ARRAY in javascript
its using a loop for over the data or manually, like this:
let data = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},
{"id":"52951699w4"}]};
let n = [data.data[0].id,data.data[1].id, data.data[2].id];
console.log(n)
output:
(3) ["5201521d42", "52049e2591", "52951699w4"]
Easy and a clean way to do this.
oldArr = {"data":[{"id":"5201521d42"},{"id":"52049e2591"},{"id":"52951699w4"}]}
oldArr = oldArr["data"].map(element => element.id)
Output: ['5201521d42', '52049e2591', '52951699w4']

javascript removing items from array

I have "scene" with graphics "objects"...
Scene.prototype.objects=new Array();
Scene.prototype.add=function(obj){
var last=this.objects.length;
this.objects[last]=obj}
Scene.prototype.remove=function(obj){
this.objects.splice(obj.id,1)}
Scene.prototype.advance=function(){
for (var id in this.objects){
var obj=this.objects[id];
obj.id=id;
obj.advance();
}
}
Scene.prototype.paint=function(context){...}
each time creating and deleting many objects. Array.prototype.splice re-index array right? Does anyone know a better technique (adding and removing on javascript Array)?
In my opinion, is another possibility to do that something like
Scene.prototype.remove=function(obj){
delete this.objects[obj.id]; // don,t care about this.objects.length
delete obj; // not necessary...
}
I have not tried it yet...
I need a good book about JavaScript :)
Your delete method wouldn't work, because objects is an Array, and obj.id is the id of the object reference stored in an element in that Array. splice would be the method to use, but you'll have to know the index of the element in the Array. Maybe you should 'remeber' it this way:
Scene.prototype.add=function(obj){
var last=this.objects.length;
obj.objectsIndex = last;
this.objects[last]=obj
}
After which you can:
Scene.prototype.remove=function(obj){
this.objects.splice(obj.objectsIndex,1)};
//reindex the objects within the objects Array
for (var i=0; i<this.objects.length;i++){
this.objects[i].objectsIndex = i;
}
}
Note: Adding the objects Array to the prototype of your Scene constructor means it will be the same for all instances (static), is that what you want?
It seems you don't actually need an array for your objects. You can use another object has hash table:
(function() {
var i = 0;
Scene.prototype.objects = {};
Scene.prototype.add = function(obj) {
var id = i++;
this.objects[id] = obj;
obj.id = id;
};
Scene.prototype.remove = function(obj){
if(obj.id in this.objects) {
delete this.objects[obj.id];
}
};
Scene.prototype.advance=function(){
for (var id in this.objects){
var obj=this.objects[id];
obj.id=id;
obj.advance();
}
};
Scene.prototype.paint=function(context){...}
}());
I'd rather avoid using new Array() instead use [] (page 114 of book I mentioned in comment - 'JavaScript: The Good Parts' by Douglas Crockford ;)).
What's more, I don't think adding objects array to Scene prototype will work as you expect. You probably want to achieve some Object-Oriented structure, which requires some acrobatic skills in JavaScript, as it uses prototypal inheritance as it is class-free.
Try something like this:
var Scene = function(initial_objects) {
this.objects = initial_objects || [];
};
Scene.prototype.add = function(obj) {
this.objects.push(obj);
};
Scene.prototype.remove_by_index = function(index) {
this.objects.splice(index, 1);
};
Scene.prototype.remove = function(obj) {
var index = this.objects.indexOf(obj);
if (index > -1) {
this.objects.splice(index, 1);
}
};
Read also this: http://javascript.crockford.com/inheritance.html

how to parse array and create new array with parsed values?

I have an array
var data = new Array("1111_3", "1231_54", "1143_76", "1758_12");
now I want to parse data[0] to get 1111.
var ids = new Array();
// example: ids = Array("1111", "1231", "1143", "1758");
and copy all ids from data to ids Array.
is it possible to do it like in php or do i need to use loops?
Thanks.
Really simple:
var ids = [];
for(var i = 0, j = data.length; i < j; ++i) {
var idString = data[i];
ids.push(idString.substring(0, idString.indexOf('_')));
}
elegance:
data.map(function(x){
return x.split('_')[0];
})
This IS part of the ECMA-262 standard.
But, if you care about supporting old outdated sub-par browsers, use jQuery (or whatever other framework you are using; almost all of them define a custom map function):
$.map(data, function(x){
return x.split('_')[0];
})
What you want to do is called a 'map.'
Some browsers support them, but if you want to be safe you can use underscore.js (http://documentcloud.github.com/underscore/)
You'd end up with either:
_(data).map(function(x){
return x.split('_')[0];
});
or
_.map(data, function(x){
return x.split('_')[0];
});
If you have a really big array it may be faster to join it to a string and split the string, rather than using any of the iterative methods to form it one by one.
var data = ["1111_3", "1231_54", "1143_76", "1758_12"];
var ids= data.join(' ').replace(/_\d+/g,'').split(' ');
alert(ids)
/* returned value: (Array)
1111,1231,1143,1758
*/

Categories