0

I have this array [ "one", "two", "three" ].

Now, given an index n, how can I find the index of the array element, in which the character at index n is located? By character at index n I mean the character of all the strings overall, i.e. of "onetwothree". For example: the character at index n = 2 is "e", for n = 3, it’s "t", for n = 4 it’s "w", etc.

The result I’m looking for is the index of the array element where the character at index n was originally found.

Examples for the given array:

Input Output … because the character at index n was
n = 2 0 "e" from "one"
n = 3 1 "t" from "two"
n = 4 1 "w" from "two"
n = 9 2 "e" from "three"
3
  • 5
    have you tried something? what goes wrong? Commented Sep 24, 2021 at 17:01
  • 1
    Make a temporary string by joining the array by empty string, then use charAt? Commented Sep 24, 2021 at 17:02
  • Yes, right, I need the index (position of array item) in that I can find the nth character. Commented Sep 24, 2021 at 17:58

2 Answers 2

1

You could find the index by taking the wanted count and subtract the length of the item.

const
    findIndex = (array, count) => array.findIndex(s => (count -= s.length) <= 0),
    array = ["one", "two", "three"];

console.log(findIndex(array, 5));

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

4 Comments

Yes, but it isn't really working. Only in this example. With the 6th character it isn't working. ``` console.log(findIndex(array, array.join('').charAt(5))); ``` Then the result is 0 because of the position of the first o.
please add how you would like to call findIndex.
@GiorgiMoniava, what should i do?
Ignore that the 5th character is a "w". "w" is the 5th character. But in what array item is the 5th caracter? => 1
0

You could traverse the array and keep track of sum of item lengths. As soon as you see the sum has exceeded the target index, it means you found the element index.

let getIndex = (data, dest) => {

    let sum = 0;

    for (let i = 0; i < data.length; i++) {
        sum += data[i].length
        if (dest < sum) {
            return i;
        }
        
    }
    
    return -1;

}

console.log(getIndex(["one", "two", "three"], 4));

Assumes dest is zero based index.

9 Comments

Thanks, but I made a mistake when I asked the question, sorry. I edited now.
@Berliner95 is this what you want?
That returns the character. I need the position of the character. In that case "1"
4 is the character position? If yes, try it with 2 and it isn't working. Because the the third charcter is in the first array item.
This answer would be better if it explained the code it regurgitates on readers.
|

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.