I have a table that follows a defined sequence that Repite : [ col , name , value1, value2 , value 3, col, name value1, value2, value3 ..col , name , value1, value2 , value 3 ]
code:
var data =["DN","Atac","1","2","3","PDA","Atac","5","6","7","EPDA","Atac","8","9","11","DN Potentielle","Atac","14","4","8"] ;
I try to split the data table col , name , values:
Code result :
var column = ["DN","PDA","EPDA","DN Potentielle"];
var name ="Atac";
var values =[ "1","2","3","5","6","7","8","9","11","14","4","8"];
how has the simplest method without a lot of code to do it
If you're sure that your data is consistent and can rely on the structure you wrote, the simplest thing would be:
var column = [];
var name = [];
var values = [];
for (var i = 0; i < data.length; i = i+5) {
column.push(data[i]);
name.push(data[i+1]);
values.push(data[i+2]);
values.push(data[i+3]);
values.push(data[i+4]);
};
name = name.filter(function(value, index, self) {
return self.indexOf(value) === index;
});
console.log(column); //["DN","PDA","EPDA","DN Potentielle"]
console.log(name); //["Atac"]
console.log(values); //["1", "2", "3", "5", "6", "7", "8", "9", "11", "14", "4", "8"]
Fiddle
Set up an object to hold the values:
var obj = { column: [], name: null, values: [] };
Then cycle over the array in groups of 5, adding the various elements to the object:
for (var i = 0, l = data.length; i < l; i+=5) {
obj.column.push(data[i]);
obj.name = data[i + 1];
// push.apply is a neat way of concatenation that doesn't
// require the creation of a new variable
obj.values.push.apply(obj.values, data.slice(i + 2, i + 5));
}
DEMO
I try to figure out what you want, and the best way is to retrieve the number value and string value without spliting it.
var data =["DN","Atac","1","2","3","PDA","Atac","5","6","7","EPDA","Atac","8","9","11","DN Potentielle","Atac","14","4","8"] ;
var columns = [];
var values = [];
$.each(data, function(k, v) {
var parsedValue = parseInt(data[k]);
if ( ! isNaN(parsedValue) ) {
values.push(parsedValue);
} else {
columns.push(v);
}
});
console.log(columns);
console.log(values);
Demo: http://jsfiddle.net/bzryqs84/1/
Related
I would like to create a simple tally system to record the data-id from the elements that are selected and combine the data-id values at the end to generate a result.
function myAnswer() {
document.getElementById('btnNxt').removeAttribute('disabled');
var myResult = '';
var iId = this.getAttribute('data-id');
myObj[page].mySel = iId;
myQueRep[page] = iId;
console.log(iId);
for (var x = 0; x < btn.length; x++) {
if (iId == x) {
btn[x].classList.add('selAnswer');
} else {
btn[x].classList.remove('selAnswer');
}
}
}
In this section, the iId variable gets the data-id value but I'm not sure how to tally the selections up and display a result based on that score.
JSFiddle of current code:
https://jsfiddle.net/mkykmg15/2/
You should be doing something with your myQueRep.
So something like:
var myQueRep = ["1", "1", "1", "2", "2", "2"]
var tally = myQueRep.reduce( function (acc, curr) {
return acc + +curr
}, 0);
console.log(tally)
I'd like to take the below array and identify all the unique values of 'fruit', and identify the corresponding counts for those fruit.
For example, in the below array, we know that there are three fruit (apples, bananas, and cherries) and that we have 2 apples, 10 bananas, and 5 cherries.
var input_data = [{"count":1,"fruit":"apple"},{"count":1,"fruit":"apple"},{"count":10,"fruit":"banana"},{"count":5,"fruit":"cherry"}]
Based on the above input, I'd like to achieve the below outputs:
desired_output_1 = ['apple','banana','cherry']
desired_output_2 = [2,10,5]
I was able to get desired_output_1 with the following function that I used from underscore.js, but I'm not sure how to attain desired_output_2.
_.uniq(_.pluck(input_data,'fruit'))
As a result, I really would like a way to attain [2,10,5] based on count for the above.
var data = [{
"count": 1,
"fruit": "apple"
}, {
"count": 1,
"fruit": "apple"
}, {
"count": 10,
"fruit": "banana"
}, {
"count": 5,
"fruit": "cherry"
}];
var fruits = [];
var counts = [];
for (var i in data) {
var index = fruits.indexOf(data[i].fruit);
if (index == -1) {
fruits.push(data[i].fruit)
counts.push(data[i].count);
} else {
counts[index] = counts[index] + data[i].count;
}
}
console.log(fruits , counts);
You may not need underscore/lodash :)
var input_data = [
{"count":1,"fruit":"apple"},
{"count":1,"fruit":"apple"},
{"count":10,"fruit":"banana"},
{"count":5,"fruit":"cherry"}
];
var result = input_data.reduce(function ( acc, current ) {
if( !acc[current.fruit] ) {
acc[current.fruit] = 0;
}
acc[current.fruit] += current.count;
return acc;
}, {});
console.log(result);
Output is an object instead of two arrays. This will keep the fruit <-> count relation.
var input_data = [{"count":1,"fruit":"apple"},{"count":1,"fruit":"apple"},{"count":10,"fruit":"banana"},{"count":5,"fruit":"cherry"}];
var fruits = [];
var counts = [];
for (var i in input_data) {
var index = fruits.indexOf(input_data[i].fruit);
if (index == -1) {
fruits.push(input_data[i].fruit)
counts.push(input_data[i].count);
} else {
counts[index] += input_data[i].count;
}
}
console.log(fruits, counts);
Suppose I have the following structure:
var obj = [{one: 1, two: 2, three: 3}, {one: 1, two: 2, three: 3}];
But I need to export this data to csv with the following output:
"1", "2", "3"
"1", "2", "3"
I've tried the following code, but it does not work:
var csvContent = "data:text/csv;charset=utf-8,";
Object.values = function (obj) {
var vals = [];
for( var key in obj ) {
if ( obj.hasOwnProperty(key) ) {
vals.push(obj[key]);
}
}
return vals;
}
Object.values(obj).forEach(function(infoArray, index) {
dataString = infoArray.join(",");
csvContent += index < obj.length ? dataString + "\n" : dataString;
});
var encodedUri = encodeURI(prepearedString);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "my_data.csv");
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
Could you please help me with this issue.
It looks as if you're converting objects to a CSV file. It's important to note that objects are basically hash maps which means that the keys are not accessed in a predictable order. Also, some of your rows may be missing a value, which would cause holes in your resulting data.
What I would do is to first transform all the rows into columns (and default to null wherever a value is missing) so that you can predictably access the values for all known columns. Then you can output a CSV header with all known headers, followed by the values.
Here's an example:
var rows = [{one: 1, two: 2, three: 3}, {one: 1, two: 2, three: 3}];
var columns = {};
rows.forEach(function (row, index) {
for (var key in row) {
if (!columns[key]) {
// Set up nullified column.
var values = [];
for (var i = 0; i < rows.length; i++) {
values.push(null);
}
columns[key] = values;
}
// Store the value in the column.
columns[key][index] = row[key];
}
});
// Print the header.
var header = Object.keys(columns);
console.log(header.join(','));
// Print the rows.
for (var i = 0; i < rows.length; i++) {
var values = header.map(function (key) { return columns[key][i]; });
console.log(values.join(','));
}
This is the output you get in the console from the above code:
one,two,three
1,2,3
1,2,3
Below is the code to extract values and have multilined them, CSV format can be managed.
var obj = [{one: 1, two: 2, three: 3}, {one: 1, two: 2, three: 3}];
var output = [];
for( var key in obj ) {
for( var k in obj[key]){
output.push(obj[key][k])
}
output.push('\n')
}
alert(output.join(''))
I get an object with partial results of match from database.
[Object { home1=4, away1=3, home2=4, away2=5, home3=6, away3=7, home4=6, away4=5, home5=3, away5=6}]
home1 it's a result of first part of home team,
away1 -> away team, home2 it's a result of second part of home team... etc etc
data in my case is each row, which i get from database.
In rows i have td with class: home1, home2, home3, away1, away2 and there are values of corresponding part of match.
I want to check if value is equal to what I got from database.
Something like this
if ($('.home1') === data[index].home1;
if($('.away2') === data[index].away2;
there should be some loop. I have no idea how to do this, I thought about an array
var array = [
{
home1: data[index].home1,
away1: data[index].away1
},
{
home2: data[index].home2,
away2: data[index].away2
},
{
home3: data[index].home3,
away3: data[index].away3
},
{
home4: data[index].home4,
away4: data[index].away4
},
{
home5: data[index].home5,
away5: data[index].away5
}
]
and then for loop:
for(var X=0; X<5;X++){
homeX == data[index].homeX
}
How can I increment name of variable by eval function? or is there any other solution? I'm very confused.
You can access object properties using operator []:
for(var i=0; i<array.length; i++)
{
var item = array[i];
var homePropertyName = 'home' + (i+1);
//now you can access homeX property of item using item[homePropertyName]
//e.g. item[homePropertyName] = data[index][homePropertyName]
}
Maybe you should use a little different structure which might fit your needs better, like this:
array = [
0: array [
"home": "Text for home",
"away": "Text for away"
],
1: array [
"home": "",
"away": ""
]
// More sub-arrays here
];
You can also initialize it with a for loop:
var array = new Array();
var i;
for (i = 0; i < 4; i++) {
array[i] = [
"home": "",
"away": ""
];
}
Or like this:
array[0]["home"] = "Text for home";
array[0]["away"] = "Text for away";
You can use this structure for the data-array also, and then use a for-loop to go through them both (like if you wish to find an element):
var result = NULL;
for (i = 0; i < array.length; i++) {
if ( (array[i]["home"] == data[index]["home"]) &&
(array[i]["away"] == data[index]["away"])
) {
// Found matching home and away
result = array[i];
break;
}
}
if (result != NULL) {
alert("Found match: " + result["home"] + " - " + result["away"]);
}
else {
alert("No match");
}
PS: Code is not tested, let me know if something is wrong.
you can access global properties in browser via window object like this (fiddle):
value1 = "ONE";
alert( window['value'+1] );
But it is not good design. You should look into how to properly format JSON object.
I have something like this:
for(var i=0; i<2; i++)
{
var item = ARR[i];
for(var x=0;x<5;x++){
var hPropertyName = 'home_p' + (x+1);
var aPropertyName = 'away_p' + (x+1);
item[hPropertyName] = ARR[i][hPropertyName];
item[aPropertyName] = ARR[i][aPropertyName];
}
and it works when i create an array:
var ARR = [
{
home_p1: 4,
away_p1: 5,
home_p2: 8,
away_p2: 9,
home_p3: 2,
away_p3: 1,
home_p4: 5,
away_p4: 3,
home_p5: 3,
away_p5: 2
},
{
home_p1: 6,
away_p1: 1,
home_p2: 1,
away_p2: 2,
home_p3: 3,
away_p3: 4,
home_p4: 5,
away_p4: 6,
home_p5: 3,
away_p5: 2
}
];
but I don't have to create an array, because i have to work on object which I get from database :
[Object { event_id=19328, home_result=3, away_result=2, home_p1=4, away_p1=3, home_p2=1, away_p2=2 ...... }]
I'm only interested in these parameters --> home_p , away_p
I want to push it to my array to looks like ARR. I think i should convert an object which I get to an array
If you are using string name for your attributes then you could try using template literals?
var someObject = {}
for(let i=0 ; i<values.length ; i++){
someObject[`home${i+1}`] = values[i];
}
and if you need it to be ES5 you could just use string concatenation. Below is a working example:
values = [1,2,3,4,5];
let someObject = {};
for(let i=0 ; i<values.length ; i++){
someObject[`value${i+1}`]=values[i];
}
console.log(someObject.value1);
console.log(someObject.value2);
console.log(someObject.value3);
console.log(someObject.value4);
console.log(someObject.value5);
Firstly, this is my json value i am getting from a php source:
[{"oid":"2","cid":"107"},{"oid":"4","cid":"98"},{"oid":"4","cid":"99"}]
After that, I want to get and oid value along with the corresponding cid value for example, oid=2 and cid=107 at one go, oid=4 and cid=98 at another and so on. I am trying to use jquery, ajax for this.
I have tried many answers for this, like: Javascript: Getting all existing keys in a JSON array and loop and get key/value pair for JSON array using jQuery but they don't solve my problem.
I tried this:
for (var i = 0; i < L; i++) {
var obj = res[i];
for (var j in obj) {
alert(j);
}
but all this did was to return the key name, which again did not work on being used.
So, you have an array of key/value pairs. Loop the array, at each index, log each pair:
var obj = [{"oid":"2","cid":"107"},{"oid":"4","cid":"98"},{"oid":"4","cid":"99"}];
for (var i = 0; i < obj.length; i++) {
console.log("PAIR " + i + ": " + obj[i].oid);
console.log("PAIR " + i + ": " + obj[i].cid);
}
Demo: http://jsfiddle.net/sTSX2/
This is an array that you have //lets call it a:
[{"oid":"2","cid":"107"},{"oid":"4","cid":"98"},{"oid":"4","cid":"99"}]
To get first element :
a[0] // this will give you first object i.e {"oid":"2","cid":"107"}
a[0]["oid"] // this will give you the value of the first object with the key "oid" i.e 2
and so on ...
Hope that helps.
`
Basically what you need is grouping of objects in the array with a property. Here I am giving two functions using which you can do this
// To map a property with other property in each object.
function mapProperties(array, property1, property2) {
var mapping = {};
for (var i = 0; i < data.length; i++) {
var item = data[i];
mapping[item[property1]] = mapping[item[property1]] || [];
mapping[item[property1]].push(item[property2]);
}
return mapping;
}
// To index the items based on one property.
function indexWithProperty(array, property) {
var indexing = {};
for (var i = 0; i < data.length; i++) {
var item = data[i];
indexing[item[property]] = indexing[item[property]] || [];
indexing[item[property]].push(item);
}
return indexing;
}
var data = [{
"oid": "2",
"cid": "107"
}, {
"oid": "4",
"cid": "98"
}, {
"oid": "4",
"cid": "99"
}];
var oidCidMapping = mapProperties(data, "oid", "cid");
console.log(oidCidMapping["2"]); // array of cids with oid "2"
var indexedByProperty = indexWithProperty(data, "oid");
console.log(indexedByProperty["4"]); // array of objects with cid "4"
May not be the exact solution you need, but I hope I am giving you the direction in which you have to proceed.
If you are willing to use other library you can achieve the same with underscorejs