How to count the array from specific JSON object value? - javascript

here is my javascript:
var json = '{"GetReportIdResult":[{"bulan":"4","total":"1728","type":"CHEESE1K","uang":"8796383"},{"bulan":"4","total":"572476","type":"ESL","uang":"5863408410"},{"bulan":"4","total":"33507","type":"WHP","uang":"235653242"},{"bulan":"5","total":"4761","type":"CHEESE1K","uang":"134877865"},{"bulan":"5","total":"245867","type":"UHT","uang":"1446787280"},{"bulan":"5","total":"47974","type":"WHP","uang":"631929807"},{"bulan":"6","total":"5762","type":"CHEESE1K","uang":"293393832"},{"bulan":"6","total":"236803","type":"UHT","uang":"2219506085"},{"bulan":"6","total":"24853","type":"WHP","uang":"386175022"}]}';
obj = JSON.parse(json);
var arrayobj = obj.GetReportIdResult.length;
alert (arrayobj);
I want to count how many type in the same bulan value, (e.g. there are 3 type = CHEESE1K, UHT, and ESL in bulan = 4)
how to do that?

There's still a typo in your JSON: you've got two commas in a row between the first two "bulan":"6" objects. But assuming you fix that...
If you're asking how to count distinct types for a particular bulan value you can do something like this:
function countTypesForBulan(resultArray, bulanVal) {
var i,
types,
count = 0;
for (i=0, types = {}; i < resultArray.length; i++)
if (resultArray[i].bulan === bulanVal && !types[resultArray[i].type]) {
types[resultArray[i].type] = true;
count++;
}
return count;
}
console.log( countTypesForBulan(obj.GetReportIdResult, "4") ); // logs 3
The above loops through the array looking for a particular bulan value, and when it finds one it checks if it has already seen the associated type - if not, it adds it to the types object and increments the counter.
Demo: http://jsfiddle.net/pAWrT/

First of all, put the JSON into a string,
else your example code wont work.
var json = '{"GetReportIdResult":[{"bulan":"4","total":"1728","type":"CHEESE1K","uang":"8796383"},{"bulan":"4","total":"572476","type":"ESL","uang":"5863408410"},{"bulan":"4","total":"33507","type":"WHP","uang":"235653242"},{"bulan":"5","total":"4761","type":"CHEESE1K","uang":"134877865"},{"bulan":"5","total":"245867","type":"UHT","uang":"1446787280"},{"bulan":"5","total":"47974","type":"WHP","uang":"631929807"},{"bulan":"6","total":"5762","type":"CHEESE1K","uang":"293393832"},,{"bulan":"6","total":"236803","type":"UHT","uang":"2219506085"},{"bulan":"6","total":"24853","type":"WHP","uang":"386175022"}]}';
Then,
Iterate with for and count in a variable or a hashmap.
Since GetReportIdResult is an array, you can:
for( var i : obj.GetReportIdResult ){
obj.GetReportIdResult[i] ... // Use at will.

This will give you a map object which will contain the count for each bulan value. For example, map['4'].count will return 3.
var i, row, arr = obj.GetReportIdResult, map = {};
for (i = 0; i < arr.length; i++) {
row = arr[i];
map[row.bulan] = map[row.bulan] || {count: 0};
if (map[row.bulan][row.type] === undefined) {
map[row.bulan][row.type] = row.type;
map[row.bulan]['count'] += 1;
}
}
console.log (JSON.stringify(map));​
JSFiddle here.

Related

Pass array values to another array

I have an array of input fields called '$inputFieldsArray' then I slice them to group by 3 into 'newArray' then I need new array value for each item to assign to another array cause in the end I need an array with input fields values grouped by 3. The end goal is to get an array which contains for 9 input fields ex [[i1,i2,i3],[i4,i5,i6],[i7,i8,i9]].
For some reason 'stringArray' output is nothing, first two arrays print correct results. It's probably some mistake I do regarding JS arrays.. Sorry js is not my main language, I try to learn it. Thanks.
Here is a screenshoot with chrome console:
Here is my function:
$($submitButton).click(function () {
// Get number of input fields
let $total = $("input[name^='bodyHeader']").length;
// Get input fields as objects
let $inputFieldsArray = $("input[name^='bodyHeader']");
let newArray = [];
let stringArray = [];
let j = 0;
// Group input fields by 3
for (let i = 0; i < $total - 1; i += 3) {
newArray[j] = $inputFieldsArray.slice(i, i + 3);
j++;
}
// Extract string values from newArray and pass them into stringArray
for (let k = 0; k < newArray.length - 1; k++) {
stringArray[k][0] = newArray[k][0].value;
stringArray[k][1] = newArray[k][1].value;
stringArray[k][2] = newArray[k][2].value;
}
// Print to test results
console.log($inputFieldsArray);
console.log(newArray);
console.log("String Array: " + stringArray);
... // Function logic is not complete
});
SOLUTION:
There is no way to declare dynamic length bidimensional array in js. Use this approach suggested by #Stephan :
stringArray[k] = [newArray[k][0].value, newArray[k][1].value,
newArray[k[2].value];
or this approach suggested by #Lorenzo Gangi:
var matrix = [],
cols = 3;
//init the grid matrix
for ( var i = 0; i < cols; i++ ) {
matrix[i] = [];
}
stringArray[k] is undefined because you defined stringArray as [] (Your browser probably threw an exception). Additionally newArray[k] starts at index 0.
You could write stringArray[k] = [newArray[k][0].value, newArray[k][1].value, newArray[k][2].value] instead.
Basically,
stringArray[k]
is undefined yet, therefore setting its [0] property wont work. May do:
stringArray[k] =newArray[k].map(el=>el.value);
Alltogether:
$($submitButton).click(function () {
let stringArray = $("input[name^='bodyHeader']").toArray().reduce((res,_,i,arr)=>((i%3==0 && res.push(arr.slice(i,i+3).map(e=>e.value))),res),[]);
});

Check for duplicates in array with randomly generated values

I'm working on exercism question and am stuck on one of the jasmine-node based tests, which says that I should be able to generate 10000 random names without any clashes (e.g. 2 randomly generated names match). This is the test:
it('there can be lots of robots with different names each', function() {
var i,
numRobots = 10000,
usedNames = {};
for (i = 0; i < numRobots; i++) {
var newRobot = new Robot();
usedNames[newRobot.name] = true;
}
expect(Object.keys(usedNames).length).toEqual(numRobots);
});
What I think I need to do is:
Create an array to hold all the names (robotNames),
Each time a name is generated, check if it exists in the array,
If it does, generate another name,
If it doesn't, add it to the array.
And here is my code so far...
"use strict";
var robotNames = [];
var name;
var Robot = function() {
this.name = this.generateName();
};
Robot.prototype.generateName = function() {
var letters = "";
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var numbers = "";
var digits = "0123456789";
// generate random characters for robot name...
for( var i=0; i < 2; i++ ) {
letters += alphabet.charAt(Math.floor(Math.random() * alphabet.length));
};
for( var i=0; i < 3; i++ ) {
numbers += digits.charAt(Math.floor(Math.random() * digits.length));
};
name = letters+numbers;
// Loop through array to check for duplicates
for(var i = 0; i < robotNames.length; i++) {
if (name == robotNames[i]) {
this.generateName();
return;
} else {
robotNames.push(name);
}
}
return name;
};
Robot.prototype.reset = function() {
this.name = this.generateName();
};
module.exports = Robot;
The test fails with an error message: "Expected 9924 to equal 10000."
The '9924' number is slightly different each time I run the test. I'm thinking this means the generateName function is eventually generating 2 matching random names. It seems as though my loop for checking duplicates is not being run and I'm not sure why.
I have tried a couple of different versions of the loop but with no success. So my questions is a) is my approach correct and there is something wrong with the syntax of my loop? or b) have I got the wrong idea about how to check for duplicates here?
Any pointers appreciated, thanks.
The problem is in this bit:
for(var i = 0; i < robotNames.length; i++) {
if (name == robotNames[i]) {
this.generateName();
return;
} else {
robotNames.push(name);
}
}
...you probably only want to push your name if NONE of the names fail to match. Here you're adding it to the list as soon as you find ONE that doesn't match. You want something more like:
for(var i = 0; i < robotNames.length; i++) {
if (name == robotNames[i]) {
return this.generateName();
}
}
robotNames.push(name);
(actually, combined with the fact that you weren't even returning the recursive call to this.generateName(), I'm not sure how your program could work...)
Find a library with an implementation for Sets. Collections.js is a good example.
One property of a set is that it doesn't have duplicates. So when you add a value to a set it will look for a duplicate and then add the value if no duplicate exists.

string occurrences in a string

I'm am working on a script to count the number of times a certain string (in this case, coordinates) occur in a string. I currently have the following:
if (game_data.mode == "incomings") {
var table = document.getElementById("incomings_table");
var rows = table.getElementsByTagName("tr");
var headers = rows[0].getElementsByTagName("th");
var allcoord = new Array(rows.length);
for (i = 1; i < rows.length - 1; i++) {
cells = rows[i].getElementsByTagName("td");
var contents = (cells[1].textContent);
contents = contents.split(/\(/);
contents = contents[contents.length - 1].split(/\)/)[0];
allcoord[i - 1] = contents
}}
So now I have my variable allcoords. If I alert this, it looks like this (depending on the number of coordinates there are on the page):
584|521,590|519,594|513,594|513,590|517,594|513,592|517,590|517,594|513,590|519,,
My goal is that, for each coordinate, it saves how many times that coordinate occurs on the page. I can't seem to figure out how to do so though, so any help would be much appreciated.
you can use regular expression like this
"124682895579215".match(/2/g).length;
It will give you the count of expression
So you can pick say first co-ordinate 584 while iterating then you can use the regular expression to check the count
and just additional information
You can use indexOf to check if string present
I would not handle this as strings. Like, the table, is an array of arrays and those strings you're looking for, are in fact coordinates. Soooo... I made a fiddle, but let's look at the code first.
// Let's have a type for the coordinates
function Coords(x, y) {
this.x = parseInt(x);
this.y = parseInt(y);
return this;
}
// So that we can extend the type as we need
Coords.prototype.CountMatches = function(arr){
// Counts how many times the given Coordinates occur in the given array
var count = 0;
for(var i = 0; i < arr.length; i++){
if (this.x === arr[i].x && this.y === arr[i].y) count++;
}
return count;
};
// Also, since we decided to handle coordinates
// let's have a method to convert a string to Coords.
String.prototype.ToCoords = function () {
var matches = this.match(/[(]{1}(\d+)[|]{1}(\d+)[)]{1}/);
var nums = [];
for (var i = 1; i < matches.length; i++) {
nums.push(matches[i]);
}
return new Coords(nums[0], nums[1]);
};
// Now that we have our types set, let's have an array to store all the coords
var allCoords = [];
// And some fake data for the 'table'
var rows = [
{ td: '04.shovel (633|455) C46' },
{ td: 'Fruits kata misdragingen (590|519)' },
{ td: 'monster magnet (665|506) C56' },
{ td: 'slayer (660|496) C46' },
{ td: 'Fruits kata misdragingen (590|517)' }
];
// Just like you did, we loop through the 'table'
for (var i = 0; i < rows.length; i++) {
var td = rows[i].td; //<-this would be your td text content
// Once we get the string from first td, we use String.prototype.ToCoords
// to convert it to type Coords
allCoords.push(td.ToCoords());
}
// Now we have all the data set up, so let's have one test coordinate
var testCoords = new Coords(660, 496);
// And we use the Coords.prototype.CountMatches on the allCoords array to get the count
var count = testCoords.CountMatches(allCoords);
// count = 1, since slayer is in there
Use the .indexOf() method and count every time it does not return -1, and on each increment pass the previous index value +1 as the new start parameter.
You can use the split method.
string.split('517,594').length-1 would return 2
(where string is '584|521,590|519,594|513,594|513,590|517,594|513,592|517,590|517,594|513,590|519')

Match any element of an array against another array

Using the following function, I am searching an array for the existence of a value;
var checkboxValues = ['large-car', 'small-car', 'automatic'];
var carType = ["large-car"];
function searchArray(arguments)
{
var o = {};
for(var i=0;i<arguments.length;i++)
{
o[arguments[i]]=null;
}
return o;
}
if (carType in searchArray(checkboxValues) )
//do something...
This condition works well when carType (which is an array itself) contains only one value but when carType contains multiple values such as,
var carType = ["large-car", "4WD"];
...then the function will return false.
To give some background, what I am trying to do is show or hide map markers (via Google Maps) based on certain conditions,
Automatic
Manual
Small Car
Large Car
4WD
Each of these values is represented as a checkbox. If "Automatic" and "Small Car" are selected, then only shown map markers who contain both those values.
If "Automatic", "Small Car" and "Large Car" are selected then only show values which match those selections.
This works if the carType array contains only a single value but as an individual vehicle may have more than one type as shown above, this is where the function fails.
What's the best way to write the function to allow for comparing multiple values in one array against that of another?
Snippet taken from this answer.
function arrayUnique(array) {
var a = array.concat();
for(var i=0; i<a.length; ++i) {
for(var j=i+1; j<a.length; ++j) {
if(a[i] === a[j])
a.splice(j--, 1);
}
}
return a;
};
And then use it like this:
var checkboxValues = ['large-car', 'small-car', 'automatic'],
carType = ["large-car"],
merged = arrayUnique(checkboxValues.concat(carType));
if (merged.length === checkboxValues.length) {...}
If you need to return the matching elements of two arrays you can do this:
function matchArrays(base, toSearch) {
var returnArray = [];
for (var i = 0; i < toSearch.length; i++) {
if (base.indexOf(toSearch[i]) !== -1) returnArray.push(toSearch[i]);
}
return returnArray;
}
Usage:
var match = matchArrays(checkboxValues, carType); // return "large-car"
Take a look at array_intersect from PHPJS, a reproduction of PHP's array_intersect function in JavaScript.
You can use js functionality to match array.
One ways is to use indexOf() function that return the index of the string if it is found in array or -1 if not found.
var checkboxValues = ["large-car", "small-car", "automatic"];
var carType = ["large-car","automatic","some car"];
function searchMatch(carType) {
var result = new Array();
for(var i=0;i < carType.length;i++) {
// If match found push the match to the result array.
if(checkboxValues.indexOf(carType[i]) != -1){
result.push(carType[i])
}
}
return result ;
}
As a result you will get ["large-car","automatic"];
if you use underscoreJs may look like this
var checkboxValues = ['large-car', 'small-car', 'automatic'];
var carType = ['small-car','automatic'];
var result=_.any(checkboxValues,function(checkbox){
return _.any(carType,function(carT){ return carT==checkbox;});
});
Try this jQuery solution:
<script type="text/javascript">
var checkboxValues = ['large-car', 'small-car', 'automatic'];
var carType = ["large-car"];
if ($.inArray(carType[0].toString(), checkboxValues ) == -1) {
return false;// if not exists
}
</script>

Finding an object and returning it based on search criteria

I have been searching online all day and I cant seem to find my answer. (and I know that there must be a way to do this in javascript).
Basically, I want to be able to search through an array of objects and return the object that has the information I need.
Example:
Each time someone connects to a server:
var new_client = new client_connection_info(client_connect.id, client_connect.remoteAddress, 1);
function client_connection_info ( socket_id, ip_address, client_status) {
this.socket_id=socket_id;
this.ip_address=ip_address;
this.client_status=client_status; // 0 = offline 1 = online
};
Now, I want to be able to search for "client_connection.id" or "ip_address", and bring up that object and be able to use it. Example:
var results = SomeFunction(ip_address, object_to_search);
print_to_screen(results.socket_id);
I am new to javascript, and this would help me dearly!
Sounds like you simply want a selector method, assuming I understood your problem correctly:
function where(array, predicate)
{
var matches = [];
for(var j = 0; j < array.length; j++)
if(predicate(j))
matches.push(j);
return matches;
}
Then you could simply call it like so:
var sample = [];
for(var j = 0; j < 10; j++)
sample.push(j);
var evenNumbers = where(sample, function(elem)
{
return elem % 2 == 0;
});
If you wanted to find a specific item:
var specificguy = 6;
var sixNumber = where(sample, function(elem)
{
return elem == specificguy;
});
What have you tried? Have you looked into converting the data from JSON and looking it up as you would in a dictionary? (in case you don't know, that would look like object['ip_address'])
jQuery has a function for this jQuery.parseJSON(object).
You're going to need to loop through your array, and stop when you find the object you want.
var arr = [new_client, new_client2, new_client3]; // array of objects
var found; // variable to store the found object
var search = '127.0.0.1'; // what we are looking for
for(var i = 0, len = arr.length; i < len; i++){ // loop through array
var x = arr[i]; // get current object
if(x.ip_address === search){ // does this object contain what we want?
found = x; // store the object
break; // stop looping, we've found it
}
}

Categories