Manipulating Strings in JavaScript Arrays

I am working with an array of arrays of data that is being retrieved from a csv file. My goal is to filter out specific indexes of an array based on the titles they contain. For instance:

If an array index includes the title "Retail", I want to return the entire index along with its values.

Here is an example of my array:

[     
    ​​[
     "Retail",
    ​​
     "22,477",
    ​​
     "24,549",
    ​​
     "19,580",
    ​​
     "15,358",
    ​​],       ​    ​
     [ 
      "Online", 

      "8,653", 

      "7,586",

      "2,432",

      "4,321"
    ],

     [ 
         "In Store", 

          "2,532", 

          "2,836", 

          "5,632",

          "7,325" 
     ]
]

I have tried two different methods, but both are returning an array of 0:

filtArr = dataList.filter(name => name.includes('Retail')) //expecting the array length 5 with "Retail" and its values

Attempt 2

 filtArr = dataList.filter(function (name) {
    return (name === "Retail")
})

The expected output should be:

console.log(filtArr) // [ 0. "Retail", 1. "22,477", 2. "24,549", 3. "19,580", 4. "15,358"

Answer №1

One effective method to determine if an array includes a specific item is by using the indexOf function. If the item is not found, it will return -1; otherwise, it will provide the index of the item.

To collect arrays that contain the word 'Retail', you can follow this approach:

let retailArrays = [];
arrayOfArrays.forEach( 
    array => {
        if( array.indexOf('Retail') !== -1) {
        retailArrays.push(array);
        };
    }
)

Answer №2

It seems like there are trailing spaces after certain names, such as "Retail" potentially being "Retail ".

Furthermore, it appears that the name is consistently the first item in the nested array, negating the need to parse the entire array.

Therefore, utilizing trim() on the initial element can eliminate the surrounding spaces.

filtArr = dataList.filter(arr => arr[0].trim() == 'Retail');

var dataList = [
  [
    "Retail",
    "22,477",
    "24,549",
    "19,580",
    "15,358",
  ],
  [
    "Online",
    "8,653",
    "7,586",
    "2,432",
    "4,321"
  ],
  [
    "In Store",
    "2,532",
    "2,836",
    "5,632",
    "7,325"
  ]
];
filtArr = dataList.filter(arr => arr[0].trim() == 'Retail');
console.log(filtArr);

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

Remembering position in JSP using Java Beans

In my "Web Engineering" assignment, I am tasked with developing a Web Application game using JSP, Servlets, and Java Beans. The game mechanics are already in place with the Servlet controlling the algorithms, JSP handling the Model/View, and Beans managing ...

A guide on updating the value of a two-dimensional array using the useState() hook

Take a look at this Codesandbox example demonstrating my issue. Experiment by typing some words into both text areas to observe the problem. I have just started learning React. My goal is to dynamically generate an svg element based on user input. I am br ...

Building a versatile dropdown menu with ReactJS and creating reusable components

I am currently working on building a dropdown menu following a tutorial, but I have encountered a roadblock. Instead of using the "props" keyword as shown by the instructor in the tutorial, I passed the props directly as arguments without using props dot. ...

Chrome has some issues with resizing the SVG Pattern element

Utilizing inline svgs, I have a svg circle filled with a pattern that should cover 100% of the container size. However, when the parent element is resized via JavaScript, the pattern no longer reflects the 100% width and height as expected. This issue seem ...

The AJAX call fails to refresh the secondary table in CodeIgniter

I have a situation where I need to display data from two tables - car producer and car model, pulled from a database. My goal is to filter the second table to only show cars from a specific producer when that producer is clicked in the first table. I attem ...

How can I access the rendered HTML element from a component in Vue 3?

This particular component is known as LayerComponent (placeholder). <script> export default { data() { return { count: 0 } } } </script> <template> <button @click="count++">You have clicked me {{ count ...

Determining the final value of the last handle in a jQuery UI slider with multiple sliders present

I need help retrieving the first and last handle values from a jQuery UI range slider when there are multiple sliders on the page. Currently, my code is set up to grab the last value from the last slider's last handle. I attempted to address this by u ...

Removing the column name from a JSON return in C# involves using a variety of techniques

Below is a JSON output I have received : [ { positionCode: "POS1", positionName: "POSITION 1", positionDescription: "", parentPosition: "POS2", }, { positionCode: "POS2", positionName: "POSITION ...

Troubleshooting lack of error responses from Backend RestAPI with Axios

I am currently facing an issue with receiving a response from my backend system (Node.js Express RestAPI). exports.send = function(req, res) { console.log("sent function running!") let contact = new Contact(req.body) contact.send() ...

Assigning a one-of-a-kind identifier to a cell within a table that was dynamically created using JavaScript and

When using JavaScript to create table cells and rows and populate them with information from a JSON file, I encounter an issue where the unique ids assigned to the table cells in my code are undefined. This causes problems when trying to reference these id ...

Is there a way to make this eval() function function properly in Internet Explorer?

My JavaScript code is fetching another JavaScript "class" from a different XHTML page. The fetched JavaScript looks like this: (function() { this.init = function() { jQuery("#__BALLOONS__tabs").tabs(); }; }) Once the f ...

Angular - Switching Displayed Information

I am currently working with Angular 4 and I am attempting to switch between contenteditable="true" and contenteditable="false" Here is what I have so far: <h1 (dblclick)="edit($event)" contentEditable="true">Double-click Here to edit</h1> Al ...

Dealing with onChange value in a date in reactjs is a common challenge that developers

I'm currently working on a basic date input component in React, but I've run into an issue when trying to change the value. Every time I update it, it always displays "1970-01-01". If anyone has any suggestions on how to fix this problem, I woul ...

Using Angular's Jasmine SpyOn function to handle errors in $resource calls

I need to write unit tests for an AngularJS service that utilizes $resource. I want to keep it isolated by using Jasmine's spyOn to spy on the query() method of $resource. In my controller, I prefer to use the shorter form of query() where you pass su ...

The concept of global object/scope and circular references in undefined cases

Trying to make sense of the outcomes from these few experiments : Experiment number 1 (in a new command line) : > _ ReferenceError: _ is not defined at repl:1:2 at REPLServer.self.eval (repl.js:110:21) at Interface.<anonymous> (repl. ...

Retrieve geographical coordinates from image metadata using JavaScript

Seeking help with extracting the GPS Exif tag from images using NodeJS. The data is currently structured as follows: { "gps": { "GPSTimeStamp": [2147483647, 76, 41], "GPSLongitude": [76, 41, 56.622], "GPSLatitude": [30, 43, 8 ...

Using Angular to pass parameters to a function

When passing a parameter to the getActiveId function in the ng-click <span class="col ion-ios7-heart-outline center" ng- click="getActiveId({{activeSlide.selected}})"> The value turns to zero in the controller, but it is passed correctly after tes ...

The difference between calling a function in the window.onload and in the body of a

In this HTML code snippet, I am trying to display the Colorado state flag using a canvas. However, I noticed that in order for the flag to be drawn correctly, I had to move certain lines of code from the window.onload() function to the drawLogo() function. ...

Utilizing window.location.pathname in Next.js for precise targeting

Are you familiar with targeting window.location.pathname in NEXT.JS? I encountered a red error while using this code in Next.js const path = window.location.pathname console.log(path) // I am able to retrieve the pathname here Then { ...

What is the resolution process for importing @angular/core/testing in TypeScript and what is the packaging structure of the Angular core framework?

When using import {Injectable} from '@angular/core';, does the module attribute in package.json point to a file that exports injectable? Also, for the format @angular/core/testing, is there a testing folder within @angular/core that contains anot ...