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.

Baz
  • 12,713
  • 38
  • 145
  • 268

3 Answers3

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

gr3co
  • 893
  • 1
  • 7
  • 15
1
var nonEmptyStrings = [];
var nonEmptyIndices = [];
["I", "am", "", "still", "here", "", "man"].forEach(function (str, i) {
    if (str != '') {
        nonEmptyStrings.push(str);
        nonEmptyIndices.push(i);
    }
});
Fuzzley
  • 306
  • 2
  • 8
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

Mina Gabriel
  • 23,150
  • 26
  • 96
  • 124