How can i get each variable into my javascript variable of a Javascript Array into my variable ??
I have this data
var Data = [
{open:100,high:104.06},
{open:103,high:105.06},
{open:107,high:106.06},
{open:109,high:107.06}
];
I have a function where i want to return each single value of this
For example
for(var i = 0; i<Data.length; i++)
var date = Data [i].open;
return date ;
Function can't return more than one value.
What you can do, is return new array with all the "open" values:
function GetDates() {
var dates = [];
for(var i = 0; i<Data.length; i++)
dates.push(Data[i].open);
return dates;
}
This way you can get the value of the second item (103) with such code:
var arrDates = GetDates();
alert(arrDates[1]);
Try with:
var Data = [
{open:100,high:104.06},
{open:103,high:105.06},
{open:107,high:106.06},
{open:109,high:107.06}
];
function getOpens(Data) {
var opens = [];
for(var i = 0; i<Data.length; i++) {
if ( opens.indexOf( Data[i].open ) == -1 ) {
opens.push( Data[i].open );
}
}
return opens;
}
var numbers = getOpens( Data ).join(' ');
It will returns an array with open properties.
Related
How can I convert my JSON to a list of arrays
My JSON is Serie :
[{"Value":10,"ValuePourcent":2},{"Value":20,"ValuePourcent":3},{"Value":51,"ValuePourcent":1}]
I would like this format:
[[10,2],[20,3],[:51,1]]
Here's my code so far:
var linq = Enumerable.From(rows);
var Serie = linq
.GroupBy("$.Year", null,
function(key, g) {
var result = {
Value: g.Sum("$.Car"),
ValuePourcent: g.Sum("$.CarPourcent")/Total*100,
};
return result;
})
.ToArray()
A simple for loop does the trick:
var data = [
{"Value":10,"ValuePourcent":2},
{"Value":20,"ValuePourcent":3},
{"Value":51,"ValuePourcent":1}
];
var result = [];
for (var i = 0; i < data.length; i++) {
var datum = data[i];
result.push([datum.Value, datum.ValuePourcent]);
}
console.log(result);
You can try to loop through the json array like this:
var json = JSON.parse("[{\"Value\":10,\"ValuePourcent\":2},{\"Value\":20,\"ValuePourcent\":3},{\"Value\":51,\"ValuePourcent\":1}]");
var newArray = [];
for(var i = 0; i < json.length; i++) {
newArray.push([
json[i].Value,
json[i].ValuePourcent
]);
}
You can use map
dataArray = [{"Value":10,"ValuePourcent":2},{"Value":20,"ValuePourcent":3},{"Value":51,"ValuePourcent":1}]
newFormat = dataArray.map(function(e){
return [e["Value"], e["ValuePourcent"]]
});
var json = [{"Value":10,"ValuePourcent":2},{"Value":20,"ValuePourcent":3},{"Value":51,"ValuePourcent":1}];
var data = $.parse(JSON(json))
var array = [];
var keys = Object.keys(json);
keys.forEach(function(key){
array.push(json[key]);
array.push(data[key]
});
I have a string like this:
var str = 'My_Type_1=SSD&My_Value_1=16GB&My_Category_1=Disk Capacity&My_Type_2=Sony
&My_Value_2=PS4&My_Category_2=Console&My_rowOrder=2,1';
The string mostly has 3 parts except the last key:
Part 1 -> My - is a Common Prefix
Part 2 -> Type or Value or Category and it can keep changing
Part 3 -> It's a numeric value binding Part 1, Part 2 and Part 3 like Spreadsheet row.
The last key is always called
My_rowOrder and it's a comma delimeted value. It specifies how to construct the output array.
In the above example, 2,1 means a key value pair of
My_Type_2=Sony&My_Value_2=PS4&My_Category_2=Console should be the first in the output array.
Using JavaScript, I would like to parse the string and create an array out of it, such that the output is:
Array
(
[ 0 ] => Array
(
[Type] => Sony
[Value] => PS4
[Category] => Console
[Row] => 2
)
[ 1 ] => Array
(
[Type] => SSD
[Value] => 16GB
[Category] => Disk Capacity
[Row] => 1
)
)
How can I do this? I am partially able to do it this way:
function StringToArray(string) {
var request = {};
var pairs = string.split('&');
for (var i = 0; i < pairs.length-1; i++) {
var pair = pairs[i].split('=');
request[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
//I think I am in the right track, but need assistance
}
Your example output uses associative arrays, which JavaScript doesn't have, but you can use an array of objects instead.
This example outputs an array of objects, in the order specified by the rowOrder parameter. It trims the prefix (defined by prefix), and also trims the row number from the end of the key.
This will also work with the parameters in any order - e.g. you can mix them and it will parse as necessary, and the rowOrder parameter can appear anywhere in the string (doesn't have to be at the end).
Demo
function StringToArray(string) {
var prefix = 'My_'; // set the prefix
var output = [], request = [];
var pairs = string.split('&');
var order;
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
if (pair[0].replace(prefix, '') == 'rowOrder') {
order = pair[1];
} else {
var key = decodeURIComponent(pair[0]);
var pos = key.lastIndexOf('_');
var trimmedKey = key.substring(0, pos).replace(prefix, '');
var row = key.substring(pos + 1);
var value = decodeURIComponent(pair[1]);
var found = false;
for (var j = 0; j < output.length; j++) {
if (output[j].Row == row) {
output[j][trimmedKey] = value;
found = true;
}
}
if (!found) {
var obj = { 'Row': row };
obj[trimmedKey] = value;
output.push(obj);
}
}
}
// do the ordering based on the rowOrder parameter
var orderList = order.split(",");
for(var k=0; k<orderList.length; k++){
for(var l=0; l<output.length; l++){
if(output[l].Row == orderList[k]){
request.push(output[l]);
break;
}
}
}
return request;
}
Outputs an array of objects in the order specified by the My_rowOrder parameter:
[
{
Row: "2",
Type: "Sony",
Value: "PS4",
Category: "Console"
},
{
Row: "1",
Type: "SSD",
Value: "16GB",
Category: "Disk Capacity"
}
]
This may works for you...
<script>
var data = "My_Type_2=Sony&My_Value_2=PS4&My_Category_2=Console";
var array = new Array();
alert(JSON.stringify(URLToArray(data)));
function URLToArray(url) {
var request = {};
var pairs = url.substring(url.indexOf('?') + 1).split('&');
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
request[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
return request;
}
</script>
Try this:
function StringToArray(string) {
var request = [[],[]];
var pairs = string.split('&');
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
request[pair[0].slice(-1)-1][decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
//console.log(request)
}
I have the following two arrays in JavaScript:
"total":[[1370923200000,"66"],[1371009600000,"42"],[1371096000000,"23"]]
"successful":[[1370923200000,"5"],[1371096000000,"2"],[1371182400000,"0"]]
I'd like to combine them into one array / object which looks something like this:
{date:1370923200000, total:"66", successful:"5"},
{date:1371009600000, total:"42"},
{date:1371096000000, total:"23", successful:"2"},
{date:1371182400000, successful:"0"}
I've tried multiple different solutions, looping through both arrays, but I can't seem to figure out an elegant solution.
Here you have:
var total = [[1370923200000, "66"],[1371009600000, "42"],[1371096000000, "23"]];
var successful = [[1370923200000, "5"],[1371096000000, "2"],[1371182400000, "0"]];
var combined = {};
for(var i=0; i<total.length; i++){
combined[total[i][0]] = {date: total[i][0], total: total[i][1]};
}
for(var i=0; i<successful.length; i++){
if(successful[i][0] in combined){
combined[successful[i][0]].successful = successful[i][1];
}
else{
combined[successful[i][0]] = {
date: successful[i][0], successful: successful[i][1]
};
}
}
var result = [];
for(var key in combined){
result.push(combined[key]);
}
alert(result.toSource());
And a working fiddle http://jsfiddle.net/eRjeZ/
A simple solution for n arrays:
var arrays = {"total":[…], "successful":[…]};
var result = [];
for (var prop in arrays) {
var arr = arrays[prop];
var i=0;
for (var j=0; j<arr.length; j++) {
var date = arr[j][0];
while (i < result.length && date > result[i].date) i++;
if (i < result.length && date == result[i].date) {
result[i][prop] = arr[j][1];
} else {
var o = {date:date};
o[prop] = arr[j][1];
result.splice(i, 0, o);
}
}
}
If you need it faster, you might use the Multiple Array Merge Using Binary Heap (see also Algorithm for N-way merge). If you've got only two lists, have a look at Most efficient way to merge two arrays of objects.
var total = [[1370923200000, "66"],[1371009600000, "42"],[1371096000000, "23"]];
var succes = [[1370923200000, "5"],[1371096000000, "2"],[1371182400000, "0"]];
var everything = {};
var output = [];
total.map( function( item ){ addToEverything( item , "total" ) } );
succes.map( function( item ){ addToEverything( item , "successful" ) } );
console.log( everything ); // This looks 'like' what you want, but better
for( var key in everything )
output.push( everything[key] );
console.log( output ); //This looks exactly like what you want
function addToEverything( item , name )
{
var key = item[0];
var entry = everything[key] || { date : key };
entry[name] = item[1];
everything[key] = entry;
}
I create an array like so
var membersList = $('#chatbox_members' , avacweb_chat.doc.body).find('li');
var onlineUsers = [];
var offLineUsers = [];
for(var i =0;i<membersList.length;i++){
var name = $(membersList[i]).text().replace("#","");
onlineUsers.push(name);
}
alert(onlineUsers);
listedUsers would come out something like so [Mr.EasyBB,Tonight,Tomorrow,Gone];
Question is if I use a two for loops one outside a setInterval and one inside to compare-
var membersList = $('#chatbox_members' , _chat.doc.body).find('li');
var onlineUsers = [];
var offLineUsers= [];
for(var i =0;i<membersList.length;i++){
var name = $(membersList[i]).text().replace("#","");
onlineUsers.push(name);
}
var int = setInterval(function() {
var newMember = ('#chatbox_members' , _chat.doc.body).find('li');
for(var i =0;i<newMember.length;i++){
var name = $(newMember[i]).text().replace("#","");
offLineUsers.push(name);
}
Which then would get:
onlineUsers = [Mr.EasyBB,Tonight,Tomorrow,Gone];
offLineUsers = [Mr.EasyBB,Tonight];
So to get the offline users I want to basically replace onlineUsers with offLineUsers which then should return Tomorrow,Gone . Though I know that an object doesn't have the function to replace so how would I go about this?
I don't think the splice function would work since you need to have parameters, and pop or shift are beginning and end of array.
for(var i = 0 ; i < offLineUsers.length ; i++)
{
for(var j = 0 ; j < onlineUsers.length ; j++)
{
if(onlineUsers[j] == offLineUsers[i])
{
onlineUsers.splice(j,1);
}
}
}
Try this snippet.
If I have understand well, maybe that helps:
function bus_dup() {
for(var i = 0; i < offLineUsers.length; i++) {
onLineUsers.splice(onLineUsers.indexOf(offLineUsers[i]),1);
}
offLineUsers = [];
}
This should do what you are looking for on a modern browser, using array.filter
var onlineUsers = ["Mr.EasyBB", "Tonight", "Tomorrow", "Gone"];
var offLineUsers = ["Mr.EasyBB", "Tonight"];
function discord(online, offline) {
return online.filter(function (element) {
return offline.indexOf(element) === -1;
});
}
console.log(discord(onlineUsers, offLineUsers));
Output
["Tomorrow", "Gone"]
On jsfiddle
If you want the difference regardless of the order of attributes passed to the function then you could do this.
var onlineUsers = ["Mr.EasyBB", "Tonight", "Tomorrow", "Gone"];
var offLineUsers = ["Mr.EasyBB", "Tonight"];
function difference(array1, array2) {
var a = array1.filter(function (element) {
return array2.indexOf(element) === -1;
});
var b = array2.filter(function (element) {
return array1.indexOf(element) === -1;
});
return a.concat(b);
}
console.log(difference(onlineUsers, offLineUsers));
console.log(difference(offLineUsers, onlineUsers));
Output
["Tomorrow", "Gone"]
["Tomorrow", "Gone"]
On jsfiddle
I'd like to split a string ("1,2,3") and return it as an int array so I wrote the following function:
function stringToIntArray(string) {
var split = {};
split = string.split(',');
var selected = {};
for (var i = 0; i <= split.length; i++) {
selected[i] = split[i];
}
return selected;
}
However split.length is always undefinied. Where's my mistake?
var selected = {};
doesn't build an array but an object, which has no length property.
You can fix your code by replacing it with
var selected = [];
If you want to return an array of numbers, you can change your code to
function stringToIntArray(string) {
var split = string.split(',');
var selected = [];
for (var i = 0; i < split.length; i++) {
selected.push(parseInt(split[i], 10));
}
return selected;
}
Note that I replaced <= with < in your loop.
Note also that for modern browsers, you can use the map function to make it simpler :
function stringToIntArray(string) {
return string.split(',').map(function(v){ return parseInt(v, 10) });
}