What is the best way to maintain the index while filtering an array?

In my code, I have two extensive arrays containing "picture names" and "picture files". The first array holds the actual names of the pictures, while the second array consists of file names. Here is an example:

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';
...

Each array contains around 1000 items in various languages (the picture files remain constant). I am reusing these arrays from a previous application to save time and avoid starting from scratch.

Functionality desired: I aim to filter the picturenames array based on user input in a textbox and then display the corresponding image from the picturefiles array.

Challenge faced: When filtering the picturenames array, I lose track of the index, making it difficult to link to the picture file name.

Below is the code snippet I am using to filter the picturenames array.

var matches = picturenames.filter(function(windowValue){
    if(windowValue) {
        return windowValue.indexOf(textToFindLower) >= 0;
    }
});

What would be the best approach to tackle this issue?

UPDATE: Although the solution suggested by Ahmed is optimal, due to time constraints and negligible performance impact, I have opted to use a for loop to search through the array as shown below:

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

Answer №1

Give this a shot:

const foundIndexes = Object.keys(picturenames).filter(pictureName => {
  pictureName.includes(textToFindLower)
});
// Get the file name using picturefiles[foundIndexes[0]]

Alternatively, consider organizing names and files together in an object like this:

const pictures = [
  {
    name: '0 - zero',
    file: 'numbers-zero.jpg',
  },
  {
    name: '1 - one',
    file: 'numbers-one.jpg',
  }
];

const foundPictures = pictures.filter(picture => picture.name.includes('zero'));
if (foundPictures[0]) console.log(foundPictures[0].file);

Answer №2

To optimize the filtering process, consider adding an additional property called index when filtering, which can then be used later on.

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

if(windowValue) {
    windowValue.index = index;
    return windowValue.comparator(textToFindLower) >= 0; // Make sure to define the comparator function
}
});

Subsequently, you can access the filtered result as shown below:

picturefiles[matches[0].index]

It's worth noting that this solution is intended for objects and not primitive string types.

In case your data type is a string, you would need to convert it to an object and store the string as a property value like name. Here's a snippet demonstrating this:

var picturenames = [];
var picturefiles = [];

picturenames.push({name:'0 - zero'});
picturenames.push({name:'1 - one'});
picturenames.push({name:'1 o\'clock'});

picturefiles.push({name:'numbers-zero.jpg'});
picturefiles.push({name:'numbers-one.jpg'});
picturefiles.push({name: 'time-1.jpg'});

var textToFindLower = "0";

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

if(windowValue) {
    windowValue.index = index;
    return windowValue.name.indexOf(textToFindLower) >= 0;
}
});

console.log(matches);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Decoding arrays in Delphi using the unserialize function

Is there a Delphi function similar to PHP's "unserialize()"? The string representation of my array is as follows: a:6:{s:15:"info_buyRequest";a:2:{s:3:"qty";i:1;s:15:"super_attribute";a:2:{i:234;s:4:"2047";i:237;s:4:"4312";}}s:15:"attributes_info" ...

What steps should be taken to switch a class from one li element to another and remove it in the process?

As I develop the navigation bar for my website, I am faced with a challenge. I want to create a button-like behavior where clicking on an li element triggers a drop-down section underneath it without using the # attribute to prevent jumping to the top of t ...

Issues with Angular ngroute: controllers are not functioning properly

In order to route my application with different themes on the same page, I plan to utilize the ngroute module. Here's an example of how I intend to achieve this: <html> <head> <title>Angular JS Views</title> ...

Sending Unique Identifier to AJAX Script

As I delve into my inaugural AJAX script, coupled with PHP pages, the intricacies of AJAX are slowly revealing themselves to me. Being relatively new to Javascript, I have managed to successfully implement the script. The task at hand involves enhancing a ...

Generate and display a random element on a webpage using Javascript or jQuery on page refresh

Currently, I am developing a website for my unique custom themes on a blogging platform. One of the features I am looking to add is a review section, where only one random review will display per page refresh. My question is, can anyone assist me in crea ...

Error encountered during Angular unit testing: Unable to read the 'id' property of a null value. (Jasmine, Karma)

I am currently working on writing unit tests for a specific component in my Angular application. The component uses a currentUser variable both in the component logic and the HTML template. I have hardcoded this variable by mocking it in every test using c ...

Turn on/off the webGL Context in webGL/three.js

I am currently working on an exciting project using three.js, and so far everything is going according to plan. The project involves displaying various meshes in different canvases, which has led me to encounter a particular issue. My goal for the project ...

Error caught: The `onClick` listener was anticipated to be a function, but instead, it was found to be of type `object` in

While attempting to delete a customer entry with a specific id, I encountered an issue in my customers.js file. Despite adding a delete function, the entry was not being removed successfully. The console displayed the following error: caught Error: Expec ...

I am experiencing an issue with my jQuery loop code not functioning properly when using the .each method within the loop

I am struggling with the following code. <input type="text" name="1" class = "inp<?=$p?>"> <input type="text" name="2" class = "inp<?=$p?>"> <input type="text" name="3" class = "inp<?=$p?>"> <input type="text" na ...

Using the AngularJS filter within the controller to only display values that are not empty

I'm facing a challenge with filtering a JSON object array to only include objects where a specific field has a value. The field I need to filter by can have any type of value, so I can't use a specific match condition. My goal is to implement t ...

Require assistance in generating three replicas of an object rather than references as it currently operates

I am encountering an issue with my code where I seem to be creating 4 references to the same object instead of 4 unique objects. When I modify a value in groupDataArrays, the same value gets updated in groupDataArraysOfficial, groupDataArraysValid, and gro ...

Tips for transferring parameters between functions in AngularJS

I'm currently working with the following piece of code: var FACEBOOK = 'facebook'; $scope.handle_credentials = function (network) { hello(network).api('me').then(function (json) { dbService.handle_credential ...

Is there a way I can invoke my function prior to the form being submitted?

For the last couple of days, I've been struggling to make this code function properly. My goal is to execute a function before submitting the form to verify if the class for each variable is consistent. You can access my code here. Any assistance you ...

Utilizing JavaScript to conceal div elements within a ul container

How can I hide specific div tags inside a ul tag using JavaScript? All div tags are currently getting hidden when I use the id of the ul tag. However, I need only the first div tag to be shown and the rest to be hidden. Here is the HTML code: <ul clas ...

Utilizing JSDoc's "includePattern" for various file formats

Recently, I delved into JSDocs and decided to implement it in my Vue.js project. However, since my project involves multiple file types like .js and .vue, I encountered a syntax error while trying to add them to the "includePattern". Here's the snippe ...

Effortlessly apply CSS styles to multiple cached jQuery variables without redundancy

Hey there, I've got this piece of code written in Javascript for a classic ASP page. Since there are no CSS classes defined, everything is handled within the Javascript itself. var $a= $('#a'), $v= $('#v'), $s= $('#s'), ...

"Discrepancy found in results between Node-Fetch POST and Firefox POST requests

I have encountered a challenge while trying to replicate a successful log-in process on a website using node-fetch after being able to do so with Firefox. The login process consists of three stages: Visiting /login which returns a sessionToken from the we ...

What is the method for combining a number with a variable designation?

Hey there, I'm having some trouble changing the variable name in a loop. I attempted to use a for loop with "stop" + i, but it didn't quite work out as I had hoped. Any assistance would be greatly appreciated! ...

Exploring the integration of angular-ui-select into an angular seed project

I set up a new project using the starter template from https://github.com/angular/angular-seed and now I'm attempting to integrate angular-ui-select for dropdown menus. I've added select.js and select.css files to my index.html as well as install ...

What sets Redux React-Native apart: Exploring the nuances between utilizing useSelector in react-redux versus connect

I believe they were identical because both extracted the content from the store. What could potentially differentiate them? ...