1

I have array like

var arr = ['8888', '2222|1', '6666', '4444|2']

and I need get index of item which include first number (before |if symbol exists). Below is helpful RegExp, you can use it, works.

var result = new RegExp('\\b' + value.replace(/^(.*)\|.*$/, '$1') + '\\b').test(arr);

value = '2222'; \\true
value = '222'; \\false
value = '2222|1'; \\false

but I need index, not if item exists.

value = '8888'; \\0
value = '2222'; \\1
value = '222'; \\-1
value = '2222|1'; \\-1

1 Answer 1

4

Use findIndex

var arr = ['8888', '2222|1', '6666', '4444|2']

const getIndex = (arr, n) => arr.findIndex(a => a.split("|")[0] === n);

console.log(getIndex(arr, "8888"))
console.log(getIndex(arr, "2222"))
console.log(getIndex(arr, "222"))
console.log(getIndex(arr, "2222|1"))

If findIndex is not supported, you could add this polyfill to make the method available in Array.prototype. You could also use a simple for loop and return when a match is found:

var arr = ['8888', '2222|1', '6666', '4444|2']

function getIndex(arr, n) {
  for (var i = 0; i < arr.length; i++) {
    if (arr[i].split("|")[0] === n)
      return i;
  }
  
  return -1;
}

console.log(getIndex(arr, "8888"))
console.log(getIndex(arr, "2222"))
console.log(getIndex(arr, "222"))
console.log(getIndex(arr, "2222|1"))

Another option suggested by T.J. Crowder:

var index = -1;
arr.some(function(a, i) {
  if (a.split("|")[0] === n) {
    index = i;
    return true;
  }
});
Sign up to request clarification or add additional context in comments.

7 Comments

Okay, now it answers the question.
Looks what I need, but older IE has problem with findIndex(), maybe some ES5 solution?
@alexso You could add the polyfill to one of your js files. Otherwise you'd have to use a for loop
@alexso - If you don't want to use a polyfill, you can do var index = -1; arr.some(function(a, i) { if (a.split("|")[0] === n) { index = i; return true; }); some is ES5.
@alexso when you write, @t you get suggested the name and you can select it. You can only mention on handle in comment. Since you already @ me, T.J's name won' show up in autofilll
|

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.