Determine string occurrence in JSON array - javascript

I have a stringified array:
JSON.stringify(arr) = [{"x":9.308,"y":6.576,"color":"yellow","restitution":0.2,"type":"static","radius":1,"shape":"square","width":0.25,"height":0.25},{"x":9.42,"y":7.488,"color":"yellow","restitution":0.2,"type":"static","radius":1,"shape":"square","width":0.25,"height":0.25}]
I need to find out how many times the word yellow occurs so I can do something like:
numYellow = 0;
for(var i=0;i<arr.length;i++){
if(arr[i] === "yellow")
numYellow++;
}
doSomething = function() {
If (numYellow < 100) {
//do something
}
If(numYellow > 100) {
//do something else
} else { do yet another thing}
}

Each element of the array is an object. Change arr[i] to arr[i].color. This does assume that the .color property is the only spot where yellow will exist, though.

This should do the trick:
var array = [{"x":9.308,"y":6.576,"color":"yellow","restitution":0.2,"type":"static","radius":1,"shape":"square","width":0.25,"height":0.25},{"x":9.42,"y":7.488,"color":"yellow","restitution":0.2,"type":"static","radius":1,"shape":"square","width":0.25,"height":0.25}]
var numYellow = 0;
for(var i=0; i<array.length; i++) {
if (array[i].color === "yellow") {
numYellow++;
}
}

Related

Error in JS duplicate array entry method

I am trying to add user inputs into an array and throw an error alert if the user enters a duplicate value. The method below works fine for duplicates, but it also throws errors for non duplicate values. I am unable to understand why. Its probably something very simple, but I'm not seeing it.
addDIN(val) {
var arr = this.din_require_list;
if (arr.length == 0) {
arr.push(val)
}
else if (arr.length > 0) {
for (var i= 0; i < arr.length; i++) {
if (val != arr[i]) {
arr.push(val);
}
else if(val == arr[i]){
alert("duplicate entry");
arr.splice(i+1,1);
}
};
};
}
,
make it simpler
function insertUnique(val){
var arr = [];
if(!arr.includes(val)){
arr.push(val)
}else{
alert("Duplicate entry");
}
}
Array.include checks whether the value exists or not in given array.
refer this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
You are pushing into the array but not exiting the loop, so the loop keeps on running and matches the value and throws the error,
What you should be doing is run the for loop separately and keep a flag if it has a duplicate or not, and if no dupes are found add the element to the array
like
for (var i= 0; i < arr.length; i++) {
if(arr[i]== val){
dupeFound==1;
console.log("duplicate")
break;
}
}
if(dupeFound!=1) array.push(val)
at risk of being simplistic
why not?
var arr = [1,2,'c','dude what'];
var lookfor = 'dude';
if(arr.indexOf(lookfor) != -1){
console.log('dude string already exists on the array')
}
Therefore
var arr = [1,2,'c','dude what'];
var add = 1;
if((arr.indexOf(add) == -1)?arr.push(add): false){
console.log('added ',add);
}else{
console.log(add,'already in array');
}
console.log(arr);

Matching contents of 2 arrays angularjs

I have 2 arrays of the following contents:
var answer = [[2,1],[1,1],[0,0]];
var selectedObject = [[1,1],[0,0],[2,1]];
I want to match the contents of both the arrays. _.Equals is not working for me in the above condition. As the contents being same are not in same position in array.
Is there any easy way to match the contents of above mentioned arrays.
Any demo code, example, or logic will be helpful.
try this way
var baz = [];
angular.forEach(answer, function(key) {
if (-1 === selectedObject.indexOf(key)) {
baz.push(key);
}
});
if(baz.length==0)
{
//Not matched
}
else
{
//matched
}
I don't know about angularjs. But basic logic goes like this,
j=0
for(i=0; i<arr_len; i++){
if(arr1[i] == arr2[i]{
j++;
}
}
if(arr_len == j){
arrays are equal.
}
Finally solved it. Using _.Equals and basic for loop. It was so simple.
if(answerArray.length != selectedAnsArray.length)
{
//wrong answer
return;
}
else
{
for(var x = 0; x < answerArray.length; x++)
{
for(var y = 0; y < selectedAnsArray.length; y++)
{
if(_.isEqual(answerArray[x],selectedAnsArray[y]))
count++;
}
}
if(count==answerArray.length)
{
//correct answer
return;
}
else
{
//wrong answer
return;
}
}

Test if object with attribute exists in an array using jQuery

Can someone please tell me the best way to check if an object within an array of objects has a type of 11?
Below is what I have but it will alert for every object in the array, can I check the whole array and get it to alert just the once at the end?
I've seen methods like grep but I've been trying and can't get it to work. I'm using jQuery.
var x;
for (x = 0; x < objects.length; x++) {
if (objects[x].type == 11) {
alert("exists");
} else {
alert("doesnt exist");
}
}
Best way is use Array.some:
var exists = objects.some(function(el) { return el.type === 11 });
In the link there is also a shim for the browser that doesn't support it.
Otherwise you can just iterate:
var exists = false;
for (var i = 0, el; !exists && (el = objects[i++]);)
exists = el.type === 11;
Once you have the exists variable set, you can just do:
if (exists) {
// do something
}
Outside the loop, in both cases.
Your code should actually do it. If you're bothered that the loop will continue uselessly, you can abort it by calling break;
if(objects[x].type == 11){
alert("exists");
break;
}
Make it a function:
function hasObjWithType11(arr) {
var x;
for (x = 0; x < arr.length; x++) {
if(arr[x].type == 11){
return true;
}
}
return false;
}
alert(hasObjWithType11([{type:1}, {type:11}]); // alerts true
This will do it
var exists = false;
for (var x = 0; x < objects.length; x++) {
if(objects[x].type == 11){
exists = true;
break;
}
}
if(exists){
alert("exists");
}
You could make the searching code more reusable by wrapping it into a separate function. That way you can externalize the condition for easier reading:
function array_contains(a, fn)
{
for (i = 0, len = a.length; i < len; ++i) {
if (fn(a[i])) {
return true;
}
}
return false;
}
if (array_contains(objects, function(item) { return item.type == 11; })) {
alert('found');
}
You could also use Array.some():
if (objects.some(function(item) {
return item.type == 11;
})) {
alert('exists');
}
For IE < 9, refer to the MDN documentation for a mock version.

Dynamic property names for loop of object Javascript

In Javascript is there a clever way to loop through the names of properties in objects in an array?
I have objects with several properties including guest1 to guest100. In addition to the loop below I'd like another one that would loop through the guestx properties without having to write it out long hand. It's going to be a very long list if I have to write the code below to results[i].guest100, that is going to be some ugly looking code.
for (var i = 0; i < results.length; i++) {
if (results[i].guest1 != "") {
Do something;
}
if (results[i].guest2 != "") {
Do something;
}
if (results[i].guest3 != "") {
Do something;
}
etcetera...
}
Try this:
for (var i = 0; i < results.length; i++) {
for (var j=0; j <= 100; j++){
if (results[i]["guest" + j] != "") {
Do something;
}
}
}
Access properties by constructing string names in the [] object property syntax:
// inside your results[i] loop....
for (var x=1; x<=100; x++) {
// verify with .hasOwnProperty() that the guestn property exists
if (results[i].hasOwnProperty("guest" + x) {
// JS object properties can be accessed as arbitrary strings with []
// Do something with results[i]["guest" + x]
console.log(results[i]["guest" + x]);
}
}
I think you'll find useful the "in" operator:
if (("guest" + i) in results[i]) { /*code*/ }
Cheers

Is there a way in javascript to find out how many times a certain string is in an array?

I have an array that I want to find the number of string 'hello' in it. Is there any way to do this?
var count = 0;
for(var i=0; i<myArray.length; i++) {
if(myArray[i] == 'hello') {
count++;
}
}
Assuming it's an array of strings,
var count = 0;
for (var i = 0; i < stringArray.length; ++i) {
if (stringArray[i] == "hello")
++count;
}
And now for something completely different functional:
var count = stringArray.filter(function(x) { return x == "hello" }).length
var arr=['no','hello',2,true,false,'hello','true','hello'];
if(arr.indexOf){
var ax= -1, count= 0;
while((ax= arr.indexOf('hello', ax+1))!= -1)++count;
}
alert(count)
Or
var count = stringArray.reduce(function(a,b){ return (b=='hello')?a+1:a},0)

Categories