3

I'm looking for a js/jquery solution for the following

I want to check an array for duplicates, lets say:

var destRes = ['BH17 7EP', 'TA2 6LL', 'OX15 4LJ', 'OX15 4LJ', 'OX15 4LJ', 'BH17 7EP', 'TA2 6LL']

and return an array that holds the first index of that value; for example for the above ex this should be the return:

var newArr = ['0', '1', '2', '2', '2', '0', '1' ]

BH17 7EP is at index 0 and 5, so in the new array the 0 and the 5 indexes should be 0, the first instance of BH17 7EP

TA2 6LL is at index 1 and 6 so in the new array the 1 and the 6 indexes should be 1, the first instance of TA2 6LL

3 Answers 3

6

you can iterate over the array and use indexOf() it always returns the first index of a value in the array. something like this:

var destRes = ['BH17 7EP', 'TA2 6LL', 'OX15 4LJ', 'OX15 4LJ', 'OX15 4LJ', 'BH17 7EP', 'TA2 6LL'];

var indexes = destRes.map(x => destRes.indexOf(x));

console.log(indexes);

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

1 Comment

Love it; Works like a charm; exactly what I was looking . Cheers
0

You could map the indices with a hash table, without using another loop for Array#indexOf.

var array = ['BH17 7EP', 'TA2 6LL', 'OX15 4LJ', 'OX15 4LJ', 'OX15 4LJ', 'BH17 7EP', 'TA2 6LL'],
    temp = Object.create(null),
    result = array.map(function (a, i) {
        return a in temp ? temp[a] : temp[a] = i;
    });
    
console.log(result);
console.log(temp);
.as-console-wrapper { max-height: 100% !important; top: 0; }

2 Comments

Doesn't in operator perform a loop in background ?
yes, but not implicit. hash table perform better than searches over the elements.
0

try this one

var destRes = ['BH17 7EP', 'TA2 6LL', 'OX15 4LJ', 'OX15 4LJ', 'OX15 4LJ', 'BH17 7EP', 'TA2 6LL'];
var newArr = [];
for (var i = (destRes.length - 1); i >= 0; i--) {
  var temp = 0;
  for (var j = 0; j < i; j++) {
    if (destRes[j] == destRes[i]) {
      temp = 1;
      break;
    }
  }
  if (temp == 1) {
    newArr[i] = j;
  } else {
    newArr[i] = i;
  }
}
console.log(newArr);

1 Comment

You could replace you second for-loop with a call to indexOf

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.