0

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.

0

3 Answers 3

2

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()

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

Comments

1
var nonEmptyStrings = [];
var nonEmptyIndices = [];
["I", "am", "", "still", "here", "", "man"].forEach(function (str, i) {
    if (str != '') {
        nonEmptyStrings.push(str);
        nonEmptyIndices.push(i);
    }
});

Comments

0
var myArray = ["I", "am", "", "still", "here", "", "man"] ;

var myNewArray = [] ;
var myOldPosition = [] ;

for(var i=0, max = myArray.length ; i < max ; i++){
    myArray[i] == '' ? true : myNewArray.push(myArray[i])

    myArray[i] == '' ? true : myOldPosition.push(i) 

}
console.log(myArray);//["I", "am", "", "still", "here", "", "man"] 
console.log(myNewArray) ;//["I", "am", "still", "here", "man"] 
console.log(myOldPosition);//[0, 1, 3, 4, 6]  

DEMO

Comments

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.