-1

I have duplicate data into array and I am trying to fetch index of each element using indexOf. but, it always give index of first record

var data = ["a","b","c","d","a",'c',"a"];
var filterData = data.filter(i=>i == "a");
filterData.forEach(element=>{
    var index = data.indexOf(element);
  console.log(index);
});

// Expected Answer : 0, 4, 6
https://stackblitz.com/edit/typescript-1ttn4m?file=index.ts

How do I get correct index of each element from original array.

2
  • To get the current index, you can use the second parameter (element, index) => { /* ... */ } Commented Oct 2, 2020 at 17:01
  • Add forEach to data too Commented Oct 2, 2020 at 17:02

2 Answers 2

1

You can do this by keeping track of where the previous element was found at. Using that value, you can skip past those elements when finding the next index.

var data = ["a","b","c","d","a",'c',"a"];
var filterData = data.filter(i => i == "a");
var previousIndex = -1;

filterData.forEach(element=>{
  var index = data.slice(++previousIndex).indexOf(element);
  console.log(index + previousIndex);
  previousIndex += index;
});

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

Comments

1

On Array.forEach, The default format is arr.forEach(callback(currentValue [, index [, array]])[, thisArg]).

You can know more on this link

var data = ["a","b","c","d","a",'c',"a"];

data.forEach((element, index) => {
  if (element === 'a') {
    console.log(index);
  }
});

3 Comments

Derek your answer is correct. buy my array has more than 3000+ element and it is not good option to run foreach on that record and match.
But to get the duplicated indexes, it will be needed to review one by one and it won't take much time.
Getting all occurrences of a value in an array is linear at best. Maybe use a different data structure and reformulate the problem--your question doesn't provide any context about the number of elements or use case so you can't expect answers to address anything beyond what you asked about.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.