0

I have created a code that checks the existence of an specific string inside array-object:

array = [{'grade': 'two'}, {'grade': 'three'}, {'grade': 'four'}];

for (var i = 0; i < array.length; i++) {  
    if (array[i].grade === 'four'){      
        remIndex = [i]; 
        break;     
    }  
}

console.log(remIndex);

This code works.

But when i tried to convert it into a function it won't work:

function getARRAYINDEX( array, callOBJ, findSTRING){

  for (var i = 0; i < array.length; i++) {
    if (array[i].callOBJ === findSTRING){
        remIndex = [i]; 
        break;
    }    
  }

  return remIndex;  
}
0

3 Answers 3

2

If you have the key name in a variable, you need to use the [] notation to access the property in the object. Replace this:

if (array[i].callOBJ === findSTRING){

with this:

if (array[i][callOBJ] === findSTRING){

Please do read this documentation to know more about working with objects.

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

Comments

0

You need to define remIndex, if it doesn't come in the if block remIndex will be undefined and on return statement it will throw an exception. You can do it like this:

function getARRAYINDEX( array, callOBJ, findSTRING){
var remIndex;
  for (var i = 0; i < array.length; i++) {

    if (array[i][callOBJ] === findSTRING){

        remIndex = [i]; 
        break;

    }

  }
  return remIndex;
}

Comments

0

When the property name is dynamic, you have to use [].

array[i][callOBJ] 

and not

array[i].callOBJ 

In the line above, callOBJ won't be evaluated and the code will try to get the property callOBJ and not the name stored in callOBJ.

const array = [{'grade': 'two'}, {'grade': 'three'}, {'grade': 'four'}];


function getARRAYINDEX( array, callOBJ, findSTRING){
  for (var i = 0; i < array.length; i++) {
    if (array[i][callOBJ] === findSTRING){
        remIndex = [i];
        break;
    }
  }
  return remIndex;
}

console.log(getARRAYINDEX(array, 'grade', 'three'));

By the way, you can achieve the same thing with findIndex ;)

const array = [{'grade': 'two'}, {'grade': 'three'}, {'grade': 'four'}];


function getARRAYINDEX( array, callOBJ, findSTRING){
  return [array.findIndex(item => item[callOBJ] === findSTRING)];
}

console.log(getARRAYINDEX(array, 'grade', 'three'));

1 Comment

i'm kind used to use like this way array[i].grade etc...i seldom use the bracket version when calling object prop.. anyways thanks mate

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.