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]}));
Related
I have an object, from which an array has to be made, where key + value pairs are converted to strings.
var obj = {'x': 1, 'y': 2, 'z':3};
I have tried to convert the content to strings:
var joined = Object.entries(obj ).join(' ');
"x,1 y,2 z,3"
and to an array of arrays
var entries = Object.entries(obj);
But it is not exactly what I need
My ideal result is
var arrayFromObject = ['x 1', 'y 2', 'z 3'];
I can probably flatten the array of arrays but maybe there is a better solution?
You can get the desired output using .map(), .join() and Object.entries():
Get an array of [key, value] pairs of a given object's properties using Object.entries().
Iterate using .map() over the array values returned in first step and use .join() to get the string in desired format.
const obj = {'x': 1, 'y': 2, 'z': 3};
const array = Object.entries(obj).map(a => a.join(' '));
console.log(array);
If you know you have a KVP set, you can do something like
const obj = {'x': 1, 'y': 2, 'z':3};
const result = Object.entries(obj).map(entry => `${entry[0]} ${entry[1]}`);
//(3) ["x 1", "y 2", "z 3"]
Object.keys(obj).map(x => `${x} ${obj[x]}`)
Explanation
Object.keys(obj) returns ["x", "y", "z"] and map then maps every key to a template literal ${x} ${obj[x]} where obj[x] is the value (y is mapped to y 2)
You can use for loop for your desired output, you could've used map but it creates performance issues if the list is large.
let obj = { x: 1, y: 2, z: 3 };
let outputArray = [];
for (let i = 0; i < Object.keys(obj).length; i++) {
outputArray.push(Object.keys(obj)[i]+' '+Object.values(obj)[i]);
}
console.log(outputArray);
const obj = {'x': 1, 'y': 2, 'z':3};
const array = Object.entries(obj).map(a => a.join(' '));
console.log(array);
I tripped over a javascript question
Initially, response from HTTP was like [...{67,90},{23,40}], Now in order to view this detail in pie chart, i had to convert it into [{x:67, y: 90}, {x:23, y:40}], but now i want this pie data to again look like [{67,90},{23,40}].
For Example:
g = [{x: 67, y:90}, {x: 23, y:40}]
I tried few things like :
1.
Object.keys(pieData).map((item) => {
return {
item.x, item.y
}
})
2.
Object.key(Object.entries(g))
Required result is:
g=[{67,90}, {23,40}]
Any help would be appreciated.
Second part of the above question is '67', '23' are actually indexes. Can we convert one of the values in index number of the array....?
If you want the x as the key and the y as the value this is what you're looking for.
var g = [{x: 67, y:90}, {x: 23, y:40}];
var result = g.map(item => ({[item.x]:item.y}));
console.log(result);
Your expected output is wrong because it contains object without key:value pairs. You should return array of arrays. Use map() and return an array containing both properties.
let g = [{x: 67, y:90}, {x: 23, y:40}]
let res = g.map(({x,y}) => [x,y]);
console.log(res)
Notice that the result g = [{67, 90}, {23, 40}] that you want is not valid javascript
I think that what you want is an array of objects [{67: 90}, {23: 40}] with the x as key and the y as value
To get that, as you post in your question you can use Array.prototype.map()
Code:
const g = [{x: 67, y:90}, {x: 23, y:40}];
const result = g.map(o => ({ [o.x]: o.y }));
console.log(result);
Given an object and a key, I am creating a function that returns an array containing all the elements of the array located at the given key that are less than 100. Basically, If the array is empty, it should return an empty array. If the array contains no elements less than 100, it should return an empty array.
If the property at the given key is not an array, it should return an empty array.
If there is no property at the key, it should return an empty array.
Here are my codes so far:
function getElementsLessThan100AtProperty(obj, key) {
if (obj.key < 100) {
return obj.key;
}
}
var obj = {
key: [1000, 20, 50, 500]
};
var output = getElementsLessThan100AtProperty(obj, 'key');
console.log(output); // --> MUST RETURN [20, 50]
Any idea what am I missing?
Use the filter method to help with this.
Note: Mozilla JavaScript Docs
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
Something like this should do the trick:
var obj = {
key: [1000, 20, 50, 500]
};
var output = obj['key'].filter(function(item){
return item < 100;
});
console.log(output); // --> MUST RETURN [20, 50]
The same can be shortened using the ES6 arrow function and an implicit return.
var output = obj['key'].filter(item => item < 100);
Using filter with arrow function will make your code much shorter.
var obj = {
key: [1000, 20, 50, 500],
};
console.log(obj['key'].filter(item => item < 100));
You can also use reduce to check if elements are less than 100, then push the value to the accumulator.
var obj = {
key: [1000, 20, 50, 500],
};
var output = obj['key'].reduce((acc, curr) => {
if (curr < 100) acc.push(curr);
return acc;
}, []);
console.log(output);
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!
I have 2 arrays in javascript.
var A = ['c++', 'java', 'c', 'c#', ...];
var B = [12, 3, 4, 25, ...];
Now from these 2 arrays i want to create another array like :
[['c++',12], ['java',3], ['c',4], ['c#', 25] ...];
Both A and B arrays are variable length in my case so how can i do this?
Underscore.js is good at that:
_.zip(*arrays)
Merges together the values of each of the arrays with the values at
the corresponding position. Useful when you have separate data sources
that are coordinated through matching array indexes. If you're working
with a matrix of nested arrays, zip.apply can transpose the matrix in
a similar fashion.
_.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]);
=> [["moe", 30, true], ["larry", 40, false], ["curly", 50, false]]
You can use this snippet if you don't to use any third party library:
var i = 0
, n = A.length
, C = [];
for (; i < n; i++) {
C.push([A[i], B[i]]);
}
function Merge(A,B){
var length = Math.min(A.length,B.length);
var result = [];
for(var i=0;i<length;i++){
result.push([ A[i], B[i] ])
}
return result;
}
I think that using a hashMap instead of 2 arrays could be a good solution for you.
In example, you could do something like the following:
var h = new Object(); // or just {}
h['c++'] = 12;
h['java'] = 3;
h['c'] = 4;
Take a look at:
http://www.mojavelinux.com/articles/javascript_hashes.html