从数组中删除空字符串,同时保持索引的记录与非空字符串 [英] Remove empty strings from array while keeping record of indexes with non empty strings

查看:145
本文介绍了从数组中删除空字符串,同时保持索引的记录与非空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以说我有一个数组如下:

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?

更新:

我需要数组的第一完好,两个阵列后产生。

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

推荐答案

遍历数组,并检查每个元素都是空的。如果它没有,添加它的位置给一个数组并将其值改为另一个数组:

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

编辑:这会留下3阵列(原件,元素,位置)。如果你宁愿只需要修改原来的使用 arr.filter()

这篇关于从数组中删除空字符串,同时保持索引的记录与非空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆