Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
405 views
in Technique[技术] by (71.8m points)

javascript - Remove empty strings from array while keeping record of indexes with non empty strings

Lets say I have an array as follows:

"I", "am", "", "still", "here", "", "man"

and from this I wish to produce the following two arrays:

"I", "am", "still", "here", "man"

 0, 1, 3, 4, 6

So, an array without the empty strings, but also an array with the array indexes of the non empty strings. What would be a nice way of producing these two arrays from the first?

UPDATE:

I need the first array intact, after the two arrays are produced.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Loop through the array and check if each element is empty. If it's not, add its position to one array and its value to another array:

var elems, positions
for (var i = 0; i < arr.length; i++){
    if (arr[i] != ""){
        elems.push(arr[i])
        positions.push(i)
    }
}

EDIT: This will leave you with 3 arrays (original, elements, positions). If you would rather just modify the original one use arr.filter()


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...