ways to extract data from nested arrays

    console.log(csvcontents.data.length - 8);
        for (let i = 7; i < csvcontents.data.length - 1; i++) {
          // console.log(csvcontents.data[i][0]);
          // arrayListFromCsvFile.push(csvcontents.data[i]);
           arrayListFromCsvFile.push(csvcontents.data[i]);
        }
        console.log(arrayListFromCsvFile); 
      }

The following code snippet displays the specified output:

[
  [
    '2021-05-18',
    '17:07:32',
    'Informational',
    'abc',
    'xyz',
    "Web user 'abc' logged in ",
    '0x00'
  ],
[
    '2021-05-18',
    '17:07:32',
    'Informational',
    'xyz',
    'abc',
    "Web user 'abc' logged in ",
    '0x10'
  ],
]

Is there a way to exclude values with indexes starting from 2,3,6?
In other words, only include '2021-05-18', '17:07:32', 'abc', and 'Web user 'abc' logged in' in both arrays.

Answer №1

Check out the array.splice() method for processing arrays in JavaScript.

const data = 
 [ [ '2021-05-18'
    , '17:07:32'
    , 'Informational'
    , 'abc'
    , 'xyz'
    , "Web user 'abc' logged in "
    , '0x00'
    ] 
  , [ '2021-05-18'
    , '17:07:32'
    , 'Informational'
    , 'xyz'
    , 'abc'
    , "Web user 'abc' logged in "
    , '0x10'
  ] ] 
      
      
data.forEach(row=>
  {
  row.splice(6,1) // beginning from the end,
  row.splice(3,1)
  row.splice(2,1)
  })
  
console.log( data )
.as-console-wrapper {max-height: 100%!important;top:0}

Answer №2

Give this a shot.


    console.log(csvcontents.data.length - 8);

    //loop through each item and create a new array with specific elements.

    const newArrayFromCsv = csvcontents.data.map((item) => {
       return [item[0], item[2], item[4], item[6]]
    })
    console.log(newArrayFromCsv); 

Answer №3

To break down an array, extract the data at specific indexes and add it to a new array.

function process() {
  console.log(dataArray.length - 8);
  for (let i = 7; i < dataArray.length - 1; i++) {
    const [a, b, c, d, e, f, g] = dataArray[i];
    newArray.push([a, b, d, f]);
  }
  console.log(newArray);
}

Example:

const arr = [0, 1, 2, 3, 4, 5, 6];
const result = [];
const [a, b, c, d, e, f, g] = arr;
result.push([a, b, d, f]);
console.log(result);

Answer №4

function alterDataArray (arr){
      return arr.map( element =>  {
         return element.filter( (el, index) => {
           return ![2,3,6].includes(index) ;
         })
      })
    }
    const information = [
          [
            '2021-05-18',
            '17:07:32',
            'Informational',
            'abc',
            'xyz',
            "Web user 'abc' logged in ",
            '0x00'
          ],
          [
            '2021-05-18',
            '17:07:32',
            'Informational',
            'xyz',
            'abc',
            "Web user 'abc' logged in ",
            '0x10'
          ],
    ]
console.log(alterDataArray(information))

Answer №5

console.log(csvcontents.data.length - 8);// Starting data at the 8th row, so counting length from there
    for (let i = 7; i < csvcontents.data.length - 1; i++) {
      // console.log(csvcontents.data[i][0]);
      // arrayListFromCsvFile.push(csvcontents.data[i]);

      csvcontents.data[i].splice(2, 1);  // Removing index 2 and shifting elements // 0 1 2 3 4 5    //2 3 5
      csvcontents.data[i].splice(2, 1);
      csvcontents.data[i].splice(4, 1);
      arrayListFromCsvFile.push(csvcontents.data[i]);
    }
    console.log(arrayListFromCsvFile);

Successful implementation after using splice() method.

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

Create a dynamic pulse line on an HTML5 Canvas

Hello everyone, I've been attempting to grasp HTML5 Canvas animation without much success. I was hoping to create the shape below by animating a custom shape every 10 seconds interval. Unfortunately, I got lost in the math and ended up manually writi ...

Issue with close request on dialog box

Whenever an icon is clicked, a dialog box containing a form should appear. The purpose of this dialog box is to either add a new tab or delete a specific tab. In my implementation, I used ReactJS, Redux, and Material-UI for building the components. Even th ...

An A-frame that continually animates a glTF model to move to the position of the camera within the A-frame

I'm currently working on a virtual reality scene using A-frame () and I'm trying to figure out how to animate a gltf model so that it always follows the camera. Essentially, I want the model to move along with the player's movements. For exa ...

Angularjs - Transferring the $scope object to a controller

While taking Angular's complimentary online course, I came across the following code snippet: app.controller('GalleryController', function(){ this.current = 0; this.setCurrent = function(imageNumber){ this.current = imageNumber || 0 ...

Displaying HTML elements based on user clicks

I am currently working with a list of categories and their corresponding items: Category 1: Item 1 Item 2 Item 3 Category 2: Item 1 Item 2 Item 3 Category 3: Item 1 Item 2 Item 3 My goal is to only show the items when a user ...

In the process of attempting to upload a .tsv file through the front end interface, I am encountering a challenge as the file remains stored on my server. What is the

I've got a function set up on my Express server that sends a file dependent on D3.JS. app.get('/dashboard', function(req, res) { var timestamp = utility.timestamp(); console.log('[' + timestamp + '] Request made to rend ...

Date filter malfunctioning

Simply put, I'm looking to showcase a date extracted from JSON. This is my attempted solution: {{ item.CreateDate | date }} {{ item.CreateDate | date : 'MM/dd/yyyy' }} However, the output I receive is: /Date(1413010800000)/ My desired ou ...

I need help figuring out how to set the country code as uneditable and also display a placeholder in react-phone-input-2 with React

How can I display the placeholder after the country code without allowing it to be edited? Currently, it's not showing up in my React functional components. Here is the code snippet: <PhoneInput className="inputTextDirLeft" ...

Getting URL parameters in VueJS after a page redirect has occurred

Currently, I am implementing a Login with Facebook feature in my VueJS application using a Third Party Service (AWS Cognito). The process involves clicking on a "Login with Facebook" button which triggers a redirect to the third party URL where a Sign Up ...

Achieving successful integration of jQuery autocomplete with PHP as the data source

Currently, I have a jQuery autocomplete field that functions using the following code snippet: var tags = ["a", "ab", "abc", "abcd", "adbce", "abcdef", "abcdefg", "abcdefgh", "abcdefghi", "abcdefghij", "abcdefghijk", "abcdefghijkl", "abcdefghijklm", "abc ...

Vue-router: I prefer to selectively choose routes for generating a dynamic loop of <router-link> components

I have successfully implemented a dynamic sidebar navigation list using router-link. <template> <div class="sidebarListItem bg-light"> <router-link v-for="route in $router.options.routes" :key="rout ...

Unable to conceal the scrollbar while keeping the div scrollable

I've been attempting to implement the techniques outlined in the guides on this site, but I'm encountering difficulty hiding the scroll bar while still maintaining scrolling functionality! My current approach involves setting the parent as relat ...

Navigating and transferring the referrer to a different webpage

Hey there, first time poster and fresh web designer on the scene! I'm currently working on a new landing page for a university at . Typically, when we create pages, we use &referrer. With the new page I've designed serving as a landing page, ...

Error: Attempting to assign a value to the non-existent property 'user' <br>    at [file path] on sqlite3

I encounter an unspecified error when I try to establish a session for the user after validating their credentials during login. I'm utilizing express-session to create the session, but it's not directly imported into the file as instructed by my ...

Understanding Question mark syntax in AngularJSWhat exactly does the question mark syntax

function searchQuery (query) { var queryResults = query ? $scope.fullList.filter(applyFilter(query)) : []; return queryResults; } Can someone explain the purpose of the question mark ? in this function? Is it indi ...

Retrieving picked options from a multi-select in Laravel using the Multiple-Select jQuery plugin

I have integrated wenzhixin/multiple-select library into my project because it offers a select all option. My goal is to display selected items as ticked which were chosen when creating the post. However, the solution I implemented does not seem to be wor ...

To optimize the code, consider replacing the file:///home/ishan/.../node_modules/chai/index.mjs require statement with a dynamic import() function that can be used in all CommonJS modules

Currently, I am using the newest version of Hardhat on WSL. Following the demonstration provided by Hardhat, I have installed the npm packages for hardhat toolbox. However, I am encountering an error that is unclear to me. Initially, I was utilizing the & ...

Activate Lottie animation upon scrolling

I recently created a unique lottie animation and successfully integrated it into my Nuxt project. I am now looking for the most effective way to manage the animation's behavior as the user scrolls through the page. I noticed that the component has an ...

"Exploring the Power of Asynchronous Promises within a Switch Statement in

My current controller setup is as follows: app.controller('myController', function ($scope, myService) { $scope.pageData = {}; myService.promiseGetDataFromServer() .then(function (response) { $scope.pageData = response ...

Sort through a collection of arrays that each contain objects

Having a challenge filtering a multidimensional array with objects within the inner arrays. Despite following examples found here, I'm still unable to successfully filter my array as desired. let arr = [ { name: 'brent', age: 123 } ]; Alth ...