Count in an array the number for each same value - javascript

My function is
var MyArray= [];
$('input:checked').each(function(index) {
MyArray= ($(this).attr('id') + ":" + $(this).val()).length;
});
My array is
Array [ "1:R1", "2:R2", "3:R3", "4:R1" ]
I would like to count the differents values and to get this object
Object {R1:2, R2:1, R3:1}

Instead of putting the values in an array and then get the values out of the array to process them and create an object, put them in the object to start with:
var map = {};
$('input:checked').each(function() {
var key = $(this).val();
if (key in map) {
map[key]++;
} else {
map[key] = 1;
}
});
Demo: http://jsfiddle.net/Guffa/0a35c6yp/

You can convert your var with this code :
var arr = [ "1:R1", "2:R2", "3:R3", "4:R1" ];
var obj = {};
for(var i=0, l=arr.length; i<l; i++) {
var parts = arr[i].split(':');
if(parts.length > 1) {
if(!obj[parts[1]]) {
obj[parts[1]] = 0;
}
obj[parts[1]]++
}
}
console.log(obj)
Or create directly the correct object :
var obj = {};
$('input:checked').each(function (index) {
var key = $(this).val();
if (!obj[key]) {
obj[key] = 0;
}
obj[key]++
});

Use a regex to capture the correct portion of the string, and add them as keys to the object, incrementing the value if it already exists:
var regex = /\d+:(R\d+)/
var obj = {};
arr.forEach(function (el) {
var key = el.match(regex)[1];
if (!obj[key]) obj[key] = 0;
obj[key]++;
});
DEMO

You could try something like that:
Write your Array into a Map and step up your value each time your map already knows the key.
for(var i = 0; i < myArray.length; i++){
var entry = myArray[i];
var key = entry.split(":")[1];
if(myMap.has(key))
myMap.set(key, myMap.get(key) + 1);
else
myMap.set(key, 1);
}
DEMO

Related

Remove duplicates from string using jquery?

How i Remove duplicates from my string
var string="1,2,3,2,4,5,4,5,6,7,6";
But i want like this
var string="1,2,3,4,5,6,7";
Yes you can do it easily, Here is the working example
data = "1,2,3,2,4,5,4,5,6,7,6";
arr = $.unique(data.split(','));
data = arr.join(",");
console.log(data);
Create the following prototype and use it to remove duplicates from any array.
Array.prototype.unique = function () {
var arrVal = this;
var uniqueArr = [];
for (var i = arrVal.length; i--; ) {
var val = arrVal[i];
if ($.inArray(val, uniqueArr) === -1) {
uniqueArr.unshift(val);
}
}
return uniqueArr;
}
Ex:
var str = "1,6,7,7,8,9";
var array1 = str.split(',');
var array1 = array1.unique();
console.log(array1); // [1,6,7,8,9]
str = array1.join();
Use the following to push unique values into a new array.
var names = [1,2,2,3,4,5,6];
var newNames = [];
$.each(names, function(index, value) {
if($.inArray(value, newNames) === -1)
newNames.push(value);
});

Push different object in an array with a for loop

I have an element structured like this:
Element ->
[{values: arrayOfObject, key:'name1'}, ... ,{values: arrayOfObjectN, key:'nameN'}]
arrayDiObject -> [Object1, Object2, ... , ObjectN] //N = number of lines in my CSV
Object1 -> {x,y}
I have to take data from a big string:
cityX#substanceX#cityY#substanceY#
I thought to make it this way, but it seems like it pushes always in the same array of objects. If I put oggetto = {values: arrayDateValue, key: key}; inside the d3.csv function, instead if I put outside the function it add me only empty objects.
Here is my code:
var final = new Array();
var oggetto;
var key;
function creaDati() {
var newdate;
var arrayDateValue = new Array();
var selString = aggiungiElemento().split("#");
//selString is an array with selString[0]: city, selString[1]: substance and so on..
var citySelected = "";
var substanceSelected = "";
for (var i = 0; i < selString.length - 1; i++) {
if (i % 2 === 0) {
citySelected = selString[i];
} else if (i % 2 !== 0) {
substanceSelected = selString[i];
key = citySelected + "#" + substanceSelected;
d3.csv("/CSV/" + citySelected + ".csv", function(error, dataset) {
dataset.forEach(function(d) {
arrayDateValue.push({
x: d.newdate,
y: d[substanceSelected]
});
});
});
oggetto = {
values: arrayDateValue,
key: key
};
arrayDateValue = [];
final.push(oggetto);
}
}
}
Any idea ?
First you should make the if statement for the city and then for the key, which you seem to be doing wrong since you want the pair indexes to be the keys and the not pair to be the city, and you are doing the opposite. And then you need to have the d3.csv and push the objects outside of the if statement, otherwise in your case you are just adding elements with citySelected="".
Try something like :
for(var i = 0; i < selString.length -1; i+=2){
cittySelected = selString[i];
substanceSelected = selString[i+1];
key = citySelected + "#" + substanceSelected;
d3.csv("/CSV/"+citySelected+".csv", function(error, dataset){
dataset.forEach(function(d){
arrayDateValue.push({x: d.newdate, y: d[substanceSelected]});
});
});
oggetto = {values: arrayDateValue, key: key};
arrayDateValue = [];
final.push(oggetto);
}
It's is not the best way to do it, but it is clearer that what you are following, i think.
In the if(i % 2 == 0) { citySelected = ... } and else if(i % 2 !== 0) { substanceSelected = ... } citySelected and substanceSelected will never come together.
The values should be in one statement:
if(...) { citySelected = ...; substanceSelected = ...; }
The string can be splitted into pairs
city1#substance1, city2#substance2, ...
with a regex (\w{1,}#\w{1,}#).
Empty the arrayDateValue after the if-statement.
Hint:
var str = "cityX#substanceX#cityY#substanceY#";
function createArr(str) {
var obj = {};
var result = [];
var key = "";
// '', cityX#substanceX, '', cityYsubstanceY
var pairs = str.split(/(\w{1,}#\w{1,}#)/g);
for (var i = 0; i < pairs.length; i++) {
if(i % 2 !== 0) {
key = pairs[i];
// d3 stuff to create values
obj = {
// Values created with d3 placeholder
values: [{x: "x", y: "y"}],
// Pair
key: key
};
result.push(obj);
}
// Here should be values = [];
}
return result;
}
var r = createArr(str);
console.log(r);
May be you can do like this;
var str = "cityX#substanceX#cityY#substanceY",
arr = str.split("#").reduce((p,c,i,a) => i%2 === 0 ? p.concat({city:c, key:a[i+1]}) : p,[]);
console.log(JSON.stringify(arr));
RESOLVED-
The problem is about d3.csv which is a asynchronous function, it add in the array when it finish to run all the other code.
I make an XMLHttpRequest for each csv file and it works.
Hope it helps.

array object manipulation to create new object

var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var expect = [
{month:"JAN",val: {"UK":"24","AUSTRIA":"64","ITALY":"21"}},
{month:"FEB",val: {"UK":"14","AUSTRIA":"24","ITALY":"22"}},
{month:"MAR",val: {"UK":"56","AUSTRIA":"24","ITALY":"51"}}
];
I have array of objects which i need to reshape for one other work. need some manipulation which will convert by one function. I have created plunker https://jsbin.com/himawakaju/edit?html,js,console,output
Main factors are Month, Country and its "AC" value.
Loop through, make an object and than loop through to make your array
var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var outTemp = {};
actual.forEach(function(obj){ //loop through array
//see if we saw the month already, if not create it
if(!outTemp[obj.month]) outTemp[obj.month] = { month : obj.month, val: {} };
outTemp[obj.month].val[obj.country] = obj.AC; //add the country with value
});
var expected = []; //convert the object to the array format that was expected
for (var p in outTemp) {
expected.push(outTemp[p]);
}
console.log(expected);
Iterate through array and create new list
var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var newList =[], val;
for(var i=0; i < actual.length; i+=3){
val = {};
val[actual[i].country] = actual[i]["AC"];
val[actual[i+1].country] = actual[i+1]["AC"];
val[actual[i+2].country] = actual[i+2]["AC"];
newList.push({month: actual[i].month, val:val})
}
document.body.innerHTML = JSON.stringify(newList);
This is the correct code... as above solution will help you if there are 3 rows and these will be in same sequnece.
Here is perfect solution :
var actual = [
{"country":"UK","month":"JAN","SR":"John P","AC":"24","PR":"2","TR":1240},
{"country":"AUSTRIA","month":"JAN","SR":"Brad P","AC":"64","PR":"12","TR":1700},
{"country":"ITALY","month":"JAN","SR":"Gim P","AC":"21","PR":"5","TR":900},
{"country":"UK","month":"FEB","SR":"John P","AC":"14","PR":"4","TR":540},
{"country":"AUSTRIA","month":"FEB","SR":"Brad P","AC":"24","PR":"12","TR":1700},
{"country":"ITALY","month":"FEB","SR":"Gim P","AC":"22","PR":"3","TR":600},
{"country":"UK","month":"MAR","SR":"John P","AC":"56","PR":"2","TR":1440},
{"country":"AUSTRIA","month":"MAR","SR":"Brad P","AC":"24","PR":"12","TR":700},
{"country":"ITALY","month":"MAR","SR":"Gim P","AC":"51","PR":"5","TR":200}
];
var tmpArray = [];
var obj =[];
for(var k=0; k<actual.length; k++){
var position = tmpArray.indexOf(actual[k].month);
if(position == -1){
tmpArray.push(actual[k].month);
val = {};
for(var i=0; i<actual.length; i++){
if(actual[i].month == actual[k].month){
val[actual[i].country] = actual[i]["AC"];
}
}
obj.push({month: actual[k].month, val:val});
}
}

how to build javascript object dynamically with array values

I need to create the object property from array values and assign some values to that for example
var main_obj = {};
var dynamic_array = ["value1", "value2", "value3", "value4"];
From dynamic_array I need to create main_obj like:
main_obj[value1][value2][value3] = some_value;
Please give me some suggestions.
dynamic_array.forEach(function(prop){
main_obj[prop] = some_value;
});
this is another way
var dynamic_array = ["value1","value2","value3"];
var value = 'your value';
function createobj(dynamic_array,value){
var count = dynamic_array.length;
var text= '';
var ended = '';
for(var i = 0; i < count; i++){
text += '{"'+dynamic_array[i]+'":';
ended +='}';
}
text += '"'+value+'"'+ended;
return JSON.parse(text);
}
console.log(createobj(dynamic_array,value));
Trying to interpretate your question, this may be a solution to what you are looking for:
function createNestedProperties(obj, array, value) {
var result = {};
var result_tmp = obj;
var i = 0;
while (i < array.length) {
if (i < (array.length - 1))
result_tmp[array[i]] = {};
else
result_tmp[array[i]] = value;
result_tmp = result_tmp[array[i]];
i++;
}
return obj;
}
used this way:
var main_obj = {"value1":{"value2":{"value3":{}}}};
var dynamic_array = ["value1", "value2", "value3"];
main_obj = createNestedProperties(main_obj, dynamic_array, {"value_Z":"new value"});
Resulting object:
{"value1":{"value2":{"value3":{"value_Z":"new value"}}}}
This function would override existing properties in main_obj if already there.
i parse through the object recursively rather than building that jQuery - How to recursively loop over an object's nested properties?
function recursiveIteration(main_obj) {
for (var property in main_obj) {
if (property == value3)
{
main_obj[property] = {"value4":test};
}
else
{
recursiveIteration(main_obj[property]);
}
}
}
recursiveIteration(main_obj);

Javascript Multidimensional Array: Add Values

So I have a multidimensional array like:
myArr = [["venue",2],["venue",16],["inning",2],["inning",4],["inning",32],["hithard", 4]]
I would like to add the similar values up. So in the end I just have:
"venue" = 18, "inning" = 38, and "hithard" = 4.
Can you give me an example of how to accomplish this? Either with Javascript and/or jQuery
Thanks!
I am not sure if you want an array or object. If object, stop it is 1st pass and tmp in below code should return you the object as Object { venue=18, inning=38, hithard=4}.
DEMO
var tmp = {}, keys;
for (var i = 0; i < myArr.length; i++) {
keys = myArr[i][0];
tmp[keys] = (tmp.hasOwnProperty(keys))?
(tmp[keys] + myArr[i][1]):myArr[i][1];
} //tmp - will return you a Object { venue=18, inning=38, hithard=4}
var output = [];
for (keys in tmp) {
output.push([keys, tmp[keys]]);
} //output will return you an array as [["venue", 18],["inning", 38],["hithard", 4]]
myArr = [["venue",2],["venue",16],["inning",2],["inning",4],["inning",32],["hithard", 4]];
values = {};
for (i=0;i<myArr.length;i++){
if ("undefined" == typeof values[myArr[i][0]]) {values[myArr[i][0]] = 0;}
values[myArr[i][0]] += myArr[i][1];
}
arr = [];
query_string = "";
for (i in values) {
// if you want it in an array:
arr.push('"' + i + '" = ' + values[i]);
query_string += (query_string.length ? "&" : "") + i + "=" + values[i];
}
​console.log(arr);​
DEMO: http://jsfiddle.net/Ta97E/2/
you can use values to create the query string
Check this code:
var final = {};
for (var i in myArr) {
var item = myArr[i];
final[item[0]] = (final[item[0]] || 0) + item[1];
}
console.log(final);​
DEMO: http://jsfiddle.net/UVJEb/
Underscore solution:
sums = _.reduce(myArr, function (obj, item) {
obj[item[0]] = (obj[item[0]] || 0) + item[1];
return obj;
}, {});
// sums = {"venue":18,"inning":38,"hithard":4}
A little dirtier in jQuery
sums = {}
$.each(myArr, function (i, value) {
sums[value[0]] = (sums[value[0]] || 0) + value[1];
});
Edit: add jQuery version

Categories

Resources