2

How can i return array position of each object in an array.

code

let targets = [1.2, 2.3, 3.5];
let targetUpdatedOn = [2018-07-06, 2018-07-06, 2018-07-06];
let liveCoinPrice = 1.3;

let targets_hit = targets.filter(function(target_value) {
  return liveCoinPrice >= target_value;
});

This what is done to find array position.

targets_hit.forEach(function(key) { 

   if(targetUpdatedOn[key] === undefined){ 
       console.log(targetUpdatedOn); 
    } 
} 

I want to return array position of each targets_hits . Any help would be thankful.

1
  • What is the value of targetUpdatedOn? Commented Jul 7, 2018 at 6:23

2 Answers 2

3

You can just do this.

targets_hit.forEach((item, index) => {
    console.log(item, index); // Item and index
    console.log(index) // Index only
});

The forEach method callback has 3 parameters.

  1. Current Value
  2. Index (Optional)
  3. Array being traversed (Optional)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

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

Comments

3

This is how you find position of each array object using array#forEach in JavaScript:

let targets = [1.2, 2.3, 3.5];

targets.forEach((element, index) => {
    console.log(`Object is ${element} and it's position is ${index}`);
});

Comments

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.