1

How can I get the index of any array having 'AAPL' in the following example code? The following code returned true or false. Instead of true or false, how can I get 0 and 2? Thanks for any help!

function test() {
  var tickers = [], isAAPL = [];
  tickers[0] = 'AAPL';
  tickers[1] = 'GOOG';
  tickers[2] = 'AAPL';
  tickers[3] = 'MSFT';
  // how to find the index of the array containing 'AAPL'?  The output should be 0 and 2.
  isAAPL = tickers.map(x => (x == 'AAPL'));
  console.log(isAAPL);
}

2 Answers 2

1
function test() {
  let tickers = ['AAPL', 'GOOG', 'AAPL', 'MSFT'];
  let found = [];
  let start = '';
  var idx = '';
  do {
    idx = tickers.indexOf('AAPL', start);
    if (~idx) {
      found.push(idx);
      start = idx + 1;
    }
  } while (~idx)
  console.log(found.join(','));
}

Execution log
2:25:24 PM  Notice  Execution started
2:25:25 PM  Info    0,2
2:25:25 PM  Notice  Execution completed

This works too:

function test1() {
  var tickers = [], isAAPL = [];
  tickers[0] = 'AAPL';
  tickers[1] = 'GOOG';
  tickers[2] = 'AAPL';
  tickers[3] = 'MSFT';
  // how to find the index of the array containing 'AAPL'?  The output should be 0 and 2.
  isAAPL = tickers.map((x,i) => {if(x == 'AAPL')return i;}).filter(e => !isNaN(e) );
  console.log(isAAPL.join(','));
}
Sign up to request clarification or add additional context in comments.

Comments

1

Here is another approach - a slight variation on the first approach in cooper's answer:

var tickers = ['AAPL', 'GOOG', 'AAPL', 'MSFT'];
var symbol = 'AAPL';
var idx = tickers.indexOf(symbol);
var isAAPL = [];
while (idx != -1) {
  isAAPL.push(idx);
  idx = tickers.indexOf(symbol, idx + 1);
}
console.log(isAAPL);

This uses indexOf() in a loop to repeatedly find the "next" occurrence.

Each time it starts at the position following the last position where the string was found.

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.