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;
}
}
Related
I was just curious, is it worth to have if condition before looping some array, that in 90% will be array of 1 item?
Code example:
const a = [3];
const aLength = a.length;
if(aLength > 1) {
for(let i = 0; i < aLength; i++) {
func(i);
}
} else {
func();
}
function func(position = 0) {
console.log('hi' + position);
}
I agree with Federico's comment, a single for loop is the most readable in this case.
Also, even though you reuse it, there is not much point to extracting a.length into aLength
const a = [3];
for(let i = 0; i < a.length; i++) {
func(i);
}
function func(position) {
console.log('hi' + position);
}
Warning: very personal perspective down there, you could achieve the same level of clarity with comments too.
Well, unless the single element case has a very specific meaning in your domain. In which case, I would separate them with two functions with very specific names as follows:
const a = [3];
if(a.length > 1) {
handleMultiple(a);
} else {
handleSingleAndWhyItIsASpecialCase(a)
}
handleMultiple(array) {
for(let i = 0; i < array.length; i++) {
func(i);
}
}
handleSingleAndWhyItIsASpecialCase(array) {
func();
}
function func(position = 0) {
console.log('hi' + position);
}
As Hamid said below, you can easily turn it into a oneliner:
[45,63,77].forEach((element, index) => console.log(index));
Consider using forEach instead of map to make your intent clear though.
Write clean code and make everyone happy.
you can eliminate if and loop:
const a=[5,6,3]
a.forEach((value,index)=>console.log('hi'+index));
Is it possible to solve this problem with bitwise operators?
Given an array of integers, find two same numbers and return one of them, for example in array [7,3,5,6,7] answer is 7. I'm trying to understand when a problem can be solved with bitwise. So far I understand that if I multiply or divide by 2 I would want to use a left shift to multiply by 2, right shift to divide by 2 and if I want to cancel out matching numbers use XOR. I was thinking I could exit a loop on the first matching pair but I now don't think I can. I've tried this.
function findIt(arr) {
var dog = 0;
for (var i = 0; i < arr.length; i++) {
if ((dog ^= arr[i]) == 0) {
dog =arr[i];
break;
}
}
return dog;
}
It's not homework, i'm just curiously learning about bitwise operations in javascript. Below solved vanilla solution.
function findIt(arr) {
var obj = {};
for (var i = 0; i < arr.length; i++) {
if (obj[arr[i]] === 1) {
return arr[i];
} else {
obj[arr[i]] = 1;
}
}
return 'no pairs found'
}
console.log(findIt([7,3,5,6,7))
As #Barmar already suggested in comments you can use nested for loops for solving the problem.
Something like this should do:
function findIt(arr) {
var cmpValue, flag = 0;
for (var i = 0; i < arr.length; i++) {
cmpValue = arr[i];
for(var j = i + 1 ; j < arr.length ; j++){
if(cmpValue^arr[i] == 0){
flag=1;
break;
}
}
if(flag == 1){
break;
}
}
if(flag == 1){
return cmpValue;
}
else{
return 'no pairs found'
}
}
console.log(findIt([7,3,5,6,7))
> 7
console.log(findIt([3,3,5,6,7))
> 3
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++;
}
}
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.
I'm trying to loop through an array to check for a specific pattern but keep getting no output afterwards. Not sure what I've done wrong! I would appreciate any help!
I am testing for the pattern at or hat.
sample = ["cat fat hat mat", "that the who"]
searchTerm = prompt("Testing?");
function count(sample, searchTerm)
{
for (i=0;i<sample.length;i++)
{
if (sample[i].indexOf(searchTerm) == -1)
{
return 0;
}
return count(sample.substring(sample.indexOf(searchTerm) + searchTerm.length), searchTerm) + 1;
}
}
alert(count(sample, searchTerm));
Rehashed code
search = ["cat fat hat mat", "that the who"];
var pattern = prompt('Search?');
function count(sample, searchTerm)
{
var count, i;
count = 0;
for (i=0; i < sample.length; i++)
{
if (sample[i].indexOf(searchTerm) !== -1)
{
count++;
}
}
return count;
}
count(search, pattern);
I've redone everything and it still gives no output.
There are a couple of problems with this code. The most immediate one is you are calling substring on an array and not a string.
return count(sample.substring ...
Likely you meant to say
return count(sample[i].substring ...
The second issue though is that you need to divide the logic up a bit. You need to divide it up into sections that count the occurrences in a word and that which iterates through the array. Today they are intertwined and results in odd behavior because you end up passing non-arrays to places expecting arrays
function count(sample, searchTerm) {
var num = 0;
for (i=0;i<sample.length;i++) {
var current = sample[i];
var index = current.indexOf(searchTerm);
while (index >= 0) {
num++;
index = current.indexOf(searchTerm, index + 1);
}
}
return num;
}
Working Fiddle: http://jsfiddle.net/wrNbL/
You don't need to use recursion here, just iterate through the array once counting if the search term matches.
function count(sample, searchTerm)
{
var count, i;
count = 0;
for (i=0; i < sample.length; i++)
{
if (sample[i].indexOf(searchTerm) !== -1)
{
count++;
}
}
return count;
}