0

I have an object as :

testArray = [{SId: 1, CModule: "End"},
             {SId: 2, CModule: "Slice"},
             {SId: 3, CModule: "Std"}]

How to return true if any of the CModule value is 'End' or return false

I have tried as :

      testArray .map(function (CModule) {
        if (CModule.CModule.indexOf('End')!==1) {
          return true;
        }
        else{ return flase } };

But this did not work when there is no value as 'End' or if it has no 'End' in its first index value

Any help is much appreciated

Sophie
  • 149
  • 1
  • 16
  • [Maybe this would help](https://stackoverflow.com/questions/49077991/how-can-i-check-if-an-object-contains-at-least-one-key-whose-value-contains-a-su) – ZombieChowder Apr 10 '20 at 11:38

2 Answers2

3

Use Array.prototype.some() for checking if atleast one element pass the condition.

let testArray = [
  {SId: 1, CModule: "End"},
  {SId: 2, CModule: "Slice"},
  {SId: 3, CModule: "Std"}
];

let res = testArray.some(item => item.CModule === 'End');
console.log(res);
Sajeeb Ahamed
  • 6,070
  • 2
  • 21
  • 30
  • Thanks for the quick solution , The same can be done using a simple for loop ? just curious to know how to – Sophie Apr 10 '20 at 11:53
  • 1
    Yes! It's a prototype of ```Array```. So you can apply this any kind of array. For more information, you can visit this https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some – Sajeeb Ahamed Apr 10 '20 at 11:55
  • The same I am checking if it contains 'End'.....as testArray.some(item => item.CModule.indexOf('End')!==-1)....Am I doing wrong here ? – Sophie Apr 10 '20 at 11:58
  • Why do you need ```indexOf```? It's not wrong though. – Sajeeb Ahamed Apr 10 '20 at 12:02
  • I m checking if value contains 'End' instead equalling it....if indexOf('End')!==-1 which certainly would give false if doesn't contain...so im using it – Sophie Apr 10 '20 at 12:04
  • 1
    If you need to check if ```End``` is a substring then it's okay. The ```some``` checks if the function inside it returns a true or false value. It's totally upto you how could you check if it returns true or false. – Sajeeb Ahamed Apr 10 '20 at 12:07
-1

The below code should work:

<script>
var testArray = [
             {SId: 1, CModule: ""},
             {SId: 2, CModule: "Slice"},
             {SId: 3, CModule: "Std"},
             {SId: 4, CModule: "End"}
             ];

      testArray .map(function (CModule) {
        if (CModule.CModule.indexOf('End')!==1) {
        console.log('true');
          return true;
        }
        else{ console.log('false');
        return flase 
        } 
        });

</script>