Merging two arrays with some logic in javascript - javascript

I try to merge something like (I show it in json)
[["Field1","0"],["Field2","0"],["Field3","0"]]
with
{"0":{"Name":"Foo","Lastname":"Bar"}}
when I do
$.extend({}, firstArray, secondArray);
I get in JSON
{
"0":{"Name":"Foo","Lastname":"Bar"},
"1":["Field1","0"],
"2":["Field2","0"]
}
as you can see the first array is some kind of mixed with the second. I want it to be wrapped up like this
{
"0":{"Name":"Foo","Lastname":"Bar"},
"1":[ "1": ["Field1","0"],"2":["Field2","0"]]
}
So later when I consume it I can get the field stuff as one array. Is the possible? I cannot get it to work. Any ideas?

Looks like you only need to add secondArray as a property of firstArray, but converted into an object. That can be accomplished like this:
firstArray["1"] = $.extend({}, {}, secondArray);
Now firstArray becomes:
{
"0":{"Name":"Foo","Lastname":"Bar"},
"1":{"0": ["Field1","0"], "1":["Field2","0"]}
}
I hope that's good enough.

firstarray = firstarray.concat(secondarray)

Related

Javascript: return the first value from arrays within an object

I am working on a javascript homework problem and am a bit stuck:
Create a function called getFirstAnimals that returns an array of all the first animals in the object.
Example: [‘bears’,’penguins’,panther’,’flea’]
I scripted the following function:
var animals = {
mammals:['bears','lions','whales','otters'],
birds:['penguins','ducks','swans','chickens'],
cats:['panther','mountain lion','leopard','snow tiger'],
insects: ['flea','mosquito','beetle','fly','grasshopper']
}
function getFirstAnimals(array) {
var firstAnimals = [];
for (key in array) {
firstAnimals.push(array[key].slice(0,1))
}
return firstAnimals;
}
console.log(getFirstAnimals(animals));
my problem is that the output I am generating is an array of arrays made up of the first animals, [Array[1], Array[1], Array[1], Array[1]], and not the strings, [‘bears’,’penguins’,panther’,’flea’]. Any suggestions on how to get the desired output is much appreciated.
Instead of pushing array[key].slice(0,1) you need to push array[key][0], where [0] is getting you the first item in the array.
You can use
firstAnimals.push(array[key][0])
for that. It gets the first element from the array
Yet another approach
var animals = {
mammals:['bears','lions','whales','otters'],
birds:['penguins','ducks','swans','chickens'],
cats:['panther','mountain lion','leopard','snow tiger'],
insects: ['flea','mosquito','beetle','fly','grasshopper']
}
function getFirstAnimals(array) {
return Object.keys(array).map(v => array[v][0]);
}
console.log(getFirstAnimals(animals));
A oneliner: console.log(animals[Object.keys(animals)[0]]);

Sort an array based on values from another array of different length

I've looked through several posts with similar with issues but I couldn't find one which solves my problem. The others all seemed to be sorting using another array of the same size or by value.
I have two arrays which look like this:
var allCategories = ['Campus', 'Building', 'Floor', 'Room', 'Lecture Theatre', 'Lab'];
var currentCategories = ['Room', 'Lab', 'Campus'];
How can I sort currentCategories so that the order matches that of allCategories?
Desired output:
currentCategories --> ['Campus', 'Room', 'Lab'];
"Sort this array by the indices of its elements in that array":
currentCategories.sort(function(a, b) {
return allCategories.indexOf(a) - allCategories.indexOf(b);
});
// => ["Campus", "Room", "Lab"]
If all that you want is the order of allCategories with the members of currentCategories, you can do the following.
allCategories.filter(function(x){return currentCategories.indexOf(x) != -1})
This assumes that you are treating each array as a set of non-repeating elements. As mentioned in the comments, this method may drop duplicate elements from the final value, or not order duplicate elements in the way you might intend.
The Array.Sort method can be supplied a custom function. You could do something like this:
currentCategories.sort(function(a, b) {
var i = allCategories.indexOf(a),
j = allCategories.indexOf(b);
return i - j;
});
I haven't checked the behaviour for when there are values in currentCategories that are not in allCategories. But then, it wouldn't be living up to its name if that were the case.
If this is a common case, you could generalise it along the following lines:
function sortByList(list) {
return function (a, b) { return list.indexOf(a) - list.indexOf(b); };
}
And call it thusly:
currentCategories.sort(sortByList(allCategories));

Multidimensional keyed array?

I want to create a multidimensional keyed array.
How do I declare the array and then push things in to it?
Is this right?
var galleryData = new Array();
$("#gallery li.gallery-image-item:not(:first)").each(function() {
galleryData.push({comment: 'comment', youTube: 'ODOIUOIhd'});
}
Thanks
That will work. An alternative syntax is
var galleryData = [];
Which is nice because yo can then do something like this:
var superGalleryData = [[],[],[]]; //creates an array of 3 arrays
Another answer suggests using an associative array but it is generally not a good idea:
http://andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/
If you want 'keyed' array I think you need something like
array['key'] = { comment: 'comment', youtube: 'ODD2345UI' };
Here's my test for you: http://jsfiddle.net/neuroflux/MtuLc/1/
var galleryData = [];
$("#gallery li.gallery-image-item:not(:first)").each(function() {
galleryData.push({comment: 'comment', youTube: 'ODOIUOIhd'});
});
Note that I fixed your missing bracket and changed your Array notation. I've also used jQuery just to output onto the page.

Split one JSON return into several objects

So, I've been looking at this for a couple hours and am out of ideas. My app is returning a single JSON object, and I need to parse the 4 data sets out of it and make 3 charts and a table. For the life of me I can't figure out how to "extract" each part. The JSON looks like:
{
"allele":{
"12426597":{
"??":4,
"CC":3,
"TT":4,
"CT":12
},
"878198":{
"??":4,
"AA":1,
"AC":15,
"CC":3
},
"6447271":{
"??":4,
"GG":14,
"AG":5
}
},
"haplo":{
"CT,AG,AC":3,
"TT,GG,AC":1,
"CC,GG,CC":1,
"TT,AG,CC":1,
"TT,GG,CC":1
},
"exercise":"p1"
}
I need to grab the data just for the three key's/IDs (12426597,878198, 6447271) and make one bar chart for each of those (requiring a data transformation <== see). Then I need to plug it into Highcharts...their API calling for an ordered arrays for the keys and values.
I thought about first making an array of the IDs:
var snpsObj = data.allele_frequency; // data returned from $.getJSON
var snpList = [];
for (prop in snpsObj) {
if (!snpsObj.hasOwnProperty(prop)) {
continue;
}
snpList.push(prop);
}
Which does get me the wanted array. And then accessing the "sub" keys like:
snpsObj.snpList[0];
...to return hopefully, something like:
{
"CC" : 23,
"CT" : 36,
"TT" : 12,
}
But that doesn't work at all. The most I could get was a return of something like:
allele_frequency : [object Object ]
I know there's something basic I'm just forgetting in my head-cold-fogged mind... Any suggestions?
Highcharts needs the keys and labels formatted in arrays, like:
categories: ['C', 'T']
data: [ 3, 9] // C=3, T=9
I think you want to access
snpsObj[ snpList[0] ]
by using bracket notation, snpsObj.snpList[0] would try to get the "snpList" property of your snpsObj object.
Btw, instead of your for-in-loop to create the array with property names, you might want to use Object.keys (even if you need to shim it to support old browsers).

Simplest way to convert a JSON object to a newly structured JSON object?

I've got a JSON object that is structured like this:
{
"xaxis": [
"foo",
"bar",
"baz"
],
"yaxis": [
333,
992,
1365
]
}
From it I'd like to create another JSON object stuctured like this:
{
"piegraph": [
["foo",333],
["bar",992],
["baz",1365]
]
}
Doing this conversion in client-side JavaScript would save me additional development and another server round-trip to fetch what is essentially the same data.
I can employ the jQuery library if that would help.
You could use Functional JavaScript:
second = { piegraph: Functional.zip([first.xaxis, first.yaxis]) };
Assuming that your first JSON string is already parsed to an object, you just have to iterate over the elements of any of the two arrays, to build the result:
var result = { piegraph: [] }; // initialize piegraph as an empty array
var l = obj.xaxis.length;
while(l--) {
result.piegraph[l] = [ obj.xaxis[l], obj.yaxis[l] ];
}
// result will look like this:
// {"piegraph":[["foo",333],["bar",992],["baz",1365]]}
No libraries needed, just a plain sequential loop. ;)
Why can't you just use a for loop something like?
for(var i = 0; xaxis.length; i++){
piegraph.push({xaxis[i], yaxis[i]);
}
This isn't hard to do manually, but the underscore.js functional library has a bunch of very handy functions, including .zip():
var piegraph = _.zip( obj.xaxis, obj.yaxis );
Looks like you want to do pair-wise matching (aka "zipping") of two arrays.
Assume array1 and array2 for x and y axes and resultArray i.e. "piegraph"
jQuery.map(array1, function(item, i){
resultArray.push(new Array(array[item, array2[i]));
}
});

Categories

Resources