0

Here i have a function .It accepts an array of object and a specific value.The array is iterated using a forEach method to ensure the provided value is already existed in any of the objects in the array.If found it returns FALSE ,or it should return true.But although it returns FALSE ,the rest of the code alse gets executed results in returning TRUE all the time.How i can return only FALSE/TRUE

 if(find_value_in_obj(all_selected,current.value)){ all_selected.push({select_elem:current,value:current.value}); console.log(all_selected); }else{ alert("you already selected the value"); } function find_value_in_obj(arr_obj,value){ arr_obj.forEach(function(elem,index,array){ if(elem.value == value){ console.log('found it '); return false; } }); console.log("i am her"); // though value already exists and should returned ,it gets executed results in returning TRUE instead return true; } 
1
  • 3
    return false; only returns from the callback you pass to forEach, it doesn't have any impact on find_value_in_obj. You should look into using Array#some. Commented Sep 18, 2016 at 5:20

3 Answers 3

2

forEach iterates over all values. You should be using .some().

And since using some is just a one-liner, you don't actually need to create a helper for it, for example (from MDN):

console.log([2, 5, 8, 1, 4].some(elem => elem > 10)); // false console.log([12, 5, 8, 1, 4].some(elem => elem > 10)); // true

Sign up to request clarification or add additional context in comments.

Comments

2

forEach cannot be broken in middle of its iteration like a regular for loop. Use a regular for loop instead. Or, if you are using ES6 then you could achieve the same thing by using .find().

function find_value_in_obj(arr_obj,value){ return !!!arr_obj.find(itm => itm == value); } 

As felix suggested, you could make use of Array.prototype.some also.

function find_value_in_obj(arr_obj,value){ return !arr_obj.some(itm => itm == value); } 

1 Comment

But find () is an es6 feature and es6 features are not fully supported in some older versions of browsers.... :(
1

You can also try using filter, which is more appropriate and clean.

 if(find_value_in_obj(all_selected,current.value)){ all_selected.push({select_elem:current,value:current.value}); console.log(all_selected); }else{ alert("you already selected the value"); } function find_value_in_obj(arr_obj,value){ var resultArray = arr_obj.filter(function(elem,index,array){ return elem.value == value; }); if(resultArray.length > 0){ return false; } console.log("i am her"); // though value already exists and should returned ,it gets executed results in returning TRUE instead return true; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.