Pushing a values in a Particular format to an array - javascript

I want to create an array dynamically which should be having a value in the format of
var dat1 = [
{ x: 0, y: 32.07 },
{ x: 1, y: 37.69 },
{ x: 2, y: 529.49 },
{ x: 3, y: 125.49 },
{ x: 4, y: 59.04 }
];
I want to store the whole thing in data into an array dynamically. I am getting these values from the json data. And I want an array to be in this format. How can I create it?
I tried this:
$.each(r_data, function(key, val) {
data1.push([{
x : i,
y : parseFloat(val.something)
}]);
i++;
});
...but didn't get the result I wanted.

Assuming you have
var data1 = [];
...and probably
var i = 0;
...prior to your code, your code will produce this structure:
var data1 = [
[ { x: 0, y: 32.07 } ],
[ { x: 1, y: 37.69 } ],
[ { x: 2, y: 529.49 } ],
[ { x: 3, y: 125.49 } ],
[ { x: 4, y: 59.04 } ]
];
Note how you've ended up with an array where each entry is another array, which in turn contains the object with the x and y properties.
I suspect you want:
var data1 = [];
var i = 0;
$.each(resultBar_data, function(key, value) {
data1.push({
x : i,
y : parseFloat(value.averagePrice)
});
i++;
});
...which just pushes the objects directly on data1, without wrapping them in extra arrays (note I've removed the [] around what's being pushed). You would access those entries like this:
console.log("The first entry is " + data1[0].x + "," + data1[0].y);
console.log("The second entry is " + data1[1].x + "," + data1[1].y);

format is an array of objects. In your following code, you are trying to push an array [{x:i, y:parseFloat(value.averagePrice)}] to the format array:
$.each(resultBar_data, function(key, value) {
format.push([{ /*array start*/
x : i,
y : parseFloat(value.averagePrice)
}] /*array end*/
);
i++;
});
Remember square brackets denote an array.
I think to fix your problem it should be:
/*i just removed the square brackets so that push now pushes an object,
not an array with a single object*/
format.push({
x : i,
y : parseFloat(value.averagePrice)
});
Hope this helps, please ask if you need more information or if I misunderstood your question!

Related

Create x y array with already created array of values

I need to create a graph with some data from an API and it has to be in the following format:
[
{
x: '2020-05-31',
y: 120
}
{
x: '2020-05-30',
y: 140
}
{
x: '2020-05-29',
y: 160
}
]
I currently can grab some data from the API in the form of 2 arrays and I'm wondering how can I get this data in a format like the above. Example arrays of data below.
[120, 140, 160]
and
["2020-05-31", "2020-05-30", "2020-05-29"]
How do I get those values into a 2 dimensional array of objects?
You can make use of the index parameter in Array#map.
const vals = [120, 140, 160],
dates = ["2020-05-31", "2020-05-30", "2020-05-29"];
const res = dates.map((x, i) => ({ x, y: vals[i] }));
console.log(res);
Both solutions assume the first array is called xArr and the second array is called yArr
Solution with a for loop:
const newArray = [];
for(let i = 0; i<xArr.length; i++){
newArray.push({
x:xArr[i],
y:yArr[i]
}
}
Solution with a map:
const newArray = xArr.map((x, i) => ({x,y:yArr[i]}));

Default value for object argument

I want to create a function with an object as parameter
The object can have for exemple three keys : x, y, z
All this keys must have default value assignment
I tried this :
function f({x:x, y:y, z: z} = {x:1,y:2,z:3}) {
return x + y + z;
}
But I have a problem
f() // return 6 => OK!
f({x: 2, y: 3, z: 4}) // return 9 => OK!
f({x: 2, y:3}) // return NaN (because z === undefined), I expect 8
How can I do this?
You can assign individual defaults when destructuring objects:
function f({ x = 1, y = 2, z = 3 } = {}) {
return x + y + z
}
console.log(f())
console.log(f({ x: 2, y: 3, z: 4 }))
console.log(f({ x: 2, y:3 }))
See the docs here, which describes array destructuring, but the same applies to objects.
What does destructuring mean? It’s a JavaScript expression that allows us to extract data from arrays, objects, maps and sets into their own variable. It allows us to extract properties from an object or items from an array, multiple at a time.
Short form: The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
Please have a look at this simple code example:
function yourFunction({
x = 1,
y = 2,
z = 3
} = {}) {
return x + y + z
}
out.innerHTML+="<br>" + yourFunction()
out.innerHTML+="<br>" + yourFunction({ x: 3, y: 3, z: 4 })
out.innerHTML+="<br>" + yourFunction({ x: 7, y: 1})
<p id="out">Results: </p>
Have a look at the docs: click

How to convert array of objects to array of arrays in js

var ph = [{x:1231,y:121},{x:131,y:11},{x:231,y:21},{x:123,y:12}]
I want to convert that to
[[1231,121],[131,11],..]
So far I have tried Array.prototype.slice.call but it is not working for me.
Use Array.prototype.map method. It iterates over an array and creates new one with the items returned by each iteration:
var ph = [{x:1231,y:121},{x:131,y:11},{x:231,y:21},{x:123,y:12}];
var result = ph.map(function(el) {
return [el.x, el.y];
});
document.body.innerHTML = '<pre>' + JSON.stringify(result, null, 4) + '</pre>'
ES6 syntax would also allow more concise notation:
var result = ph.map(el => [el.x, el.y]);
You can use map() to iterate and generate new array based on old array elements.
var arr = [{
x: 1231,
y: 121
}, {
x: 131,
y: 11
}, {
x: 231,
y: 21
}, {
x: 123,
y: 12
}];
var res = arr.map(function(v) {
return [v['x'], v['y']];
});
document.write('<pre>' + JSON.stringify(res, null, 3) + '</pre>');
You can use Array.prototype.map. In ES6 it can done like
var ph = [{x:1231,y:121},{x:131,y:11},{x:231,y:21},{x:123,y:12}];
var arr = ph.map(elem => [elem.x, elem.y]);
document.write(JSON.stringify(arr));

Javascript: Most Efficient Way of Summing Multiple Arrays by Key

I have a JSON object returned from a web service, which is an array of objects. I need to add the "data" arrays together to form a summed array. The JSON response looks like this:
[
{
"data":[
0,3,8,2,5
],
"someKey":"someValue"
},
{
"data":[
3,13,1,0,5
],
"someKey":"someOtherValue"
}
]
There could be N amount of objects in the array. The desired output for the above example would be:
[3, 16, 9, 2, 10]
I was intending on creating an empty array variable (var arr), then looping over the objects, and for each object, loop through the "data" key and for each key increment the corresponding key in arr by the value.
Is there a more efficient way of doing this using some sort of merge function?
How about this, I believe it should work for all cases.
var data = [{
"data": [
0, 3, 8, 2, 5
],
"someKey": "someValue"
}, {
"data": [
3, 13, 1, 0, 5
],
"someKey": "someOtherValue"
}];
var datas = data.reduce(function(a, b) {
b.data.forEach(function(x, i) {
a[i] = a[i] || 0;
a[i] += x;
});
return a;
}, []);
console.log(datas);
If every object has the same data length, you can try with:
var input; // Your input data
var output = [];
for (var i = 0; i < input[0].data.length; i++) {
output[i] = input.reduce(function(prev, item) {
return +(item.data[i]) + prev;
}, 0);
}
console.log(output);
// [3, 16, 9, 2, 10]
If every object has different data size:
var input; // Your input data
var i = 0, output = [];
while (true) {
var outOfIndex = true;
var sum = input.reduce(function(prev, item) {
if (item.data[i] !== undefined) {
outOfIndex = false;
}
return +(item.data[i]) + prev;
}, 0);
if (outOfIndex) {
break;
}
output[i++] = sum;
}
console.log(output);
// [3, 16, 9, 2, 10]
Slightly less imperative solution:
//zip takes two arrays and combines them per the fn argument
function zip(left, right, fn) {
var shorter = (right.length > left.length) ? left : right;
return shorter.map(function(value, i) {
return fn(left[i], right[i]);
});
}
//assuming arr is your array of objects. Because were using
//zip, map, and reduce, it doesn't matter if the length of the
//data array changes
var sums = arr
.map(function(obj) { return obj.data; })
.reduce(function(accum, array) {
//here we want to combine the running totals w/the current data
return zip(accum, array, function(l, r) { return l + r; });
});

IndexOf and .splice() equivalent for objects

I have the following code (jsfiddle):
var obj = {
x: 48,
y: 13
};
var main = [{
x: 8,
y: 3
}, {
x: 82,
y: 31
}, {
x: 48,
y: 13
}, {
x: 28,
y: 31
}];
var result = $.grep(main, function (e) {
return ((e.x == obj.x) && (e.y == obj.y));
});
var index = main.indexOf(obj);
if (result.length > 0)
main.splice(index, 1);
I understand it's an array of objects. Is there any other way besides iterating it myself to retrieve the index and then splice it?
You actually already have the index. The callback of the $.grep() method takes as second argument the index. So you could write something like this:
var obj = {
x: 48,
y: 13
};
var main = [{
x: 8,
y: 3
}, {
x: 82,
y: 31
}, {
x: 48,
y: 13
}, {
x: 28,
y: 31
}];
var index;
var result = $.grep(main, function (e, i) {
var res = (e.x == obj.x) && (e.y == obj.y);
if (res) {
index = i;
}
return res;
});
if (result.length > 0)
main.splice(index, 1);
This will give you the last index, if there are multiple occurances. If you want the first index (as you would get it using indexOf on an array) you need to make sure that once index is set, it doesn't get overriden.
FIDDLE
var index = main.indexOf(obj);
The indexOf Array method does compare by equality, which for objects means their identity. You can only use it if your main array was like:
var main = [{x:8,y:3}, {x:82,y:31}, obj, {x:28,y:31}];
// ^^^
Is there any other way besides iterating it myself to retrieve the index?
If you search for something that does not compare by equality, then no. Of course you can write a special helper function for that purpose (just like indexOf is one). Don't fear to do so (and you're not missing a native alternative)!
Apparently what you are looking for is an associative array. You could rewrite your main array as an "associative array" (actually an object):
var main = {
"8": {
"3": {...}
},
"82": {
"31": {...}
},
// etc.
};
Then what you are looking for is simply:
main[obj.x][obj.y]

Categories