如何在不丢失索引的情况下过滤数组?

dev*_*mat 5 javascript arrays filter

我有两个非常长的数组包含"图片名称"和"图片文件".第一个表示图片的实际名称,而第二个表示文件名.例如:

picturenames[0] = '0 - zero';
picturenames[1] = '1 - one';
picturenames[2] = '1 o\'clock';
...
picturefiles[0] = 'numbers-zero.jpg';
picturefiles[1] = 'numbers-one.jpg';
picturefiles[2] = 'time-1.jpg';
...
Run Code Online (Sandbox Code Playgroud)

我用几种语言在每个数组中有大约1000个项目(图片文件总是相同的).我正在从以前的应用程序"回收"这些数组,以节省一些时间,避免重新编写所有内容.

理想的功能:在文本框中使用用户输入我想过滤picturenames数组,然后显示相应的picturefiles图像.

我面临的问题:当我过滤picturenames数组时,我丢失了索引,我无法"到达"图片文件名.

这是我用来过滤picturenames数组的代码.

var matches = picturenames.filter(function(windowValue){
    if(windowValue) {
        return windowValue.indexOf(textToFindLower) >= 0;
    }
});
Run Code Online (Sandbox Code Playgroud)

最好的方法是什么?

更新:Ahmed提出的解决方案是最好的解决方案,但由于时间原因和可忽略的性能问题,我只是使用for循环来搜索数组,如下所示:

        var matchesCounter = new Array();

        for (i = 0; i < picturenames.length; i++) {
            if (picturenames[i].indexOf(textToFindLower) >= 0) {
                matchesCounter.push(i);
            }
        }

        console.log(matchesCounter);

        for (i = 0; i < matchesCounter.length; i++) {
            console.log(picturenames[i]);
            console.log(picturefiles[i]);
        }
Run Code Online (Sandbox Code Playgroud)

I. *_*med 2

您可以在过滤期间添加一个属性index,然后您可以使用index.

var matches = picturenames.filter(function(windowValue, index){

if(windowValue) {
    windowValue.index = index;
    return windowValue.comparator(textToFindLower) >= 0;// Need to define comparator function
}
});
Run Code Online (Sandbox Code Playgroud)

稍后您可以使用如下方式访问:

picturefiles[matches[0].index]
Run Code Online (Sandbox Code Playgroud)

但是,该解决方案适用于对象,而不是原始类型字符串。

如果您的数据类型是字符串,那么您必须转换为对象并将字符串作为属性值,例如name. 片段如下:

var matches = picturenames.filter(function(windowValue, index){

if(windowValue) {
    windowValue.index = index;
    return windowValue.comparator(textToFindLower) >= 0;// Need to define comparator function
}
});
Run Code Online (Sandbox Code Playgroud)