Eliminating data columns within a javascript array

I have a set of data that has been organized into an array format. My goal is to retain the original dataset while creating a modified array as output within a function. This modified array will then be used in subsequent functions to visualize graph data.

The initial array of data looks like this:

dataArray = [
['Day', '1', '2', '3', '4', '5', '6'],
['Day -7',0,0,0,0,0,0,],
['Day -6',0,0,0,0,0,0,],
['Day -5',0,0,0,0,0,0,],
['Day -4',0,0,0,0,0,0,],
['Day -3',0,0,0,0,0,0,],
['Day -2',0,0,0,0,0,0,],
];

In addition, I have created an array called switch:

switch = [];
switch[0] = false;
switch[1] = false;
switch[2] = false;
switch[3] = false;
switch[4] = false;
switch[5] = false;
switch[6] = false;

Within my code, my objective is to iterate through the length of the switch array and remove the corresponding column or index from each line in the dataArray array.

function workingDataArray(){
    workingArray = null;
    workingArray = dataArray.slice();
    var switchLength = switch.length;
    for (var i = 0; i < switchLength; i++) {
        if(!switch[i]){
            // Code to remove items at this position if the switch is true
        }
    }
    return workingArray;
}

The concept here is that by setting switch[3] and switch[5] to true, the output will be:

['Day', '1', '2', '4', '6']
['Day -7',0,0,0,0,]
['Day -6',0,0,0,0,]
['Day -5',0,0,0,0,]
['Day -4',0,0,0,0,]
['Day -3',0,0,0,0,]
['Day -2',0,0,0,0,]

This approach makes sense to me, but I am open to suggestions on how to improve it and welcome any guidance in the right direction.

Answer №1

To achieve this result, utilize the combination of .map and .filter in the given manner:

var switcher = [true, true, false, false, false, true, true],

dataArray = [
    ['Day', '1', '2', '3', '4', '5', '6'],
    ['Day -7',0,0,0,0,0,0],
    ['Day -6',0,0,0,0,0,0],
    ['Day -5',0,0,0,0,0,0],
    ['Day -4',0,0,0,0,0,0],
    ['Day -3',0,0,0,0,0,0],
    ['Day -2',0,0,0,0,0,0],
];


function reduceMyArray(arr){
    return arr.map(function(x, index){
        return x.filter(function(y, index1){
            return switcher[index1] === true;
        });
    });
}

var x = reduceMyArray(dataArray);

The use of .map will provide the final array output after processing, where each row is filtered by checking the values based on the switcher index being true.

Answer №2

Function.prototype.applyCustomModel = function( model ){
    var result = [];
    this.forEach( function( item ){
        if( item instanceof Function ){
            var temp = [];
            item.forEach( function( element, index ){
                if( !model[ index ] )
                    temp.push( element );
            });
            result.push( temp );
        }
    });
    return result;
}

var selector = [true, true, false, true],
    dataList = [
        ['Item', 'A', 'B', 'C'],
        ['Item 1', 123,321,213],
        ['Item 2', 675,453,231],
        ['Item 3', 987,543,678],
    ];

dataList.applyCustomModel( selector );

Answer №3

If you want to achieve this, utilizing the .slice() method is crucial as it allows you to make changes without affecting the original array. The process is quite simple - create an array of indexes that need to be removed, adjust for the removal using splice(), and then return the modified version of the array.

var data = [
    ['Day', '1', '2', '3', '4', '5', '6'],
    ['Day -7',0,0,1,0,0,0],
    ['Day -6',0,0,1,0,0,0],
    ['Day -5',0,0,1,0,0,0],
    ['Day -4',0,0,1,0,0,0],
    ['Day -3',0,0,1,0,0,0],
    ['Day -2',0,0,1,0,0,0],
];

function removeItems(dataArray, indices) {
    return dataArray.map(function (row) {
        var adjustment = 0;
        var _row = row.slice();
        indices.forEach(function (index) {
            _row.splice(index - adjustment, 1);
            adjustment++;
        });
        return _row;
    });
}  

var switches = [false, false, false, true, false, true, false];
var indicesToRemove = switches.reduce(function (acc, condition, idx) {
  if (condition) {
    acc.push(idx);
  }
  return acc;
}, []);
console.log("---- MODIFIED ARRAY ----");
console.log(removeItems(data, indicesToRemove));
console.log("\n---- ORIGINAL ARRAY ----");
console.log(data);

Answer №4

  1. switch is a reserved keyword, so it's important to rename the variable switch.
  2. To manipulate arrays, you can utilize splice for removing elements and map for transforming an array into another.

Check out the code snippet below:

dataArray = [
['Day', '1', '2', '3', '4', '5', '6'],
['Day -7',0,0,0,0,0,0,],
['Day -6',0,0,0,0,0,0,],
['Day -5',0,0,0,0,0,0,],
['Day -4',0,0,0,0,0,0,],
['Day -3',0,0,0,0,0,0,],
['Day -2',0,0,0,0,0,0,],
                        ];

myNewSwitch = [];
myNewSwitch[0] = false;
myNewSwitch[1] = false;
myNewSwitch[2] = false;
myNewSwitch[3] = true;
myNewSwitch[4] = false;
myNewSwitch[5] = true;
myNewSwitch[6] = false;

function UpdateAndTransformArray(){
    var updatedArr = dataArray.map(x => x);
    var j = 0;
    var switchLength = myNewSwitch.length;
    for (var i = 0; i < switchLength; i++) {
       
        if(myNewSwitch[i]){
           updatedArr[0].splice(j,1);
           j = i - 1 ;
         }
          j++;
    }
    return updatedArr;
}

console.log(UpdateAndTransformArray());

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

Choose an option to adjust the transparency of the image

I'm struggling with a select option and need some assistance. I have a select dropdown list where I want the image opacity to change from 0.3 to 1 when selected or onchange event occurs. The catch is, I can't use the value of the option because i ...

Send an array from PHP to jQuery using AJAX, then send the array back from jQuery to PHP

I am facing a dilemma where I am passing an array from PHP to jQuery AJAX using `json_encode` and storing it in an empty array declared in the jQuery script as `var myarr = []`. Later in the same script, I am sending the same array `myarr` back to the PHP ...

Why is my ForEach loop only capturing the final item in the array?

I am encountering an issue with a function that I want to perform for every item in my array. It seems to only trigger for the last item in the array, and I am unsure of how to address this problem: $scope.PlayMovie =function(){ angular.forEach($scope ...

Instructions for adding an onfocus event listener to an input field in order to dynamically change the formatting of associated labels

I'm looking to change the style of my input labels to a more fancy look by implementing the .fancyclass style when using the onfocus event on the input field. I am curious to know how this can be achieved through event listeners in Javascript? ...

What exactly is contained within a NULL array in the C programming language?

If a function in C receives NULL as input for an array, and the function returns array[0] or any number, what will be returned - 0 or NULL? Would it make a difference if mathematical operations were performed with array[0]? And most importantly, how can ...

Problem regarding data-th-id

I am facing an issue with a button that triggers a modal view and trying to capture its value using JavaScript. Here is how it's set up: <button type="button" class="btn btn-outline-primary btn-sm" data-toggle="modal" data-target="#myModal" d ...

Creating a multipart/form-data POST request in Angular2 and performing validation on the input type File

I am working on sending an image (base64) via a POST request and waiting for the response. The POST request should have a Content-Type of multipart/form-data, and the image itself should be of type image/jpg. This is what the POST request should look like ...

Retrieve content from the pushState state object

$(function(){ $('button').click(function(e){ e.preventDefault(); var nextUrl = 'page1.html'; var previousUrl = window.location.href; $.get(nextUrl, function(data){ $('body').ht ...

What is the best way to implement validation in a textarea to restrict the word count to a minimum of 250 and a maximum

I want to implement jQuery validation for a textarea field, with a requirement of 250 minimum words and 1000 maximum words. Additionally, I need to display the word count in a span tag next to the text area. How can I ensure that this validation works even ...

JavaScript program that continuously reads and retrieves the most recent data from a dynamically updating JSON file at regular intervals of every few seconds

I am a beginner in JavaScript and I'm facing an issue with displaying the most recent values from a .json file on an HTML page. The file is updated every 10 seconds, and I am also reading it every 10 seconds, but I'm not getting the latest data. ...

Modify Bootstrap TouchSpin's initial value

Struggling to update the initial value displayed in TouchSpin, it seems like there is no direct way to do it. While it's possible to change other values like the maximum value, attempts to set the initval directly have failed. $("input[name=&apos ...

Combine a variety of small 2D matrices to create a larger one

Looking to interlace small matrices into a larger one? Imagine having 4 matrices of size 4x4, and you want to combine them to create an 8x8 matrix like the image below: https://i.sstatic.net/MLZGy.png The order in which the small matrices are obtained det ...

Range Overflow Memory Problem

I'm having an issue with running a macro to copy and paste columns from one worksheet to another. Everything works fine when I only select a few columns, but as soon as I try to copy all the columns I need, I encounter an error. I believe my syntax is ...

A regular expression in Javascript that can be used to identify at least one word starting with a number among multiple words, with a

Currently, I am utilizing JavaScript Regex to validate an input field based on specific conditions: The value must consist of only alphabets and numbers There should be a minimum of two words (more than two are allowed) Only one word can start with a num ...

In JavaScript, the checkboxes in all columns of a table with over 200 rows can be set, but only the checkboxes in the rows

Seeking help to implement toggle buttons for checkboxes on a page with a large table fetched from an external system. The table can have over 200 rows or more. Currently, I am facing an issue where I can only access and manipulate the visible checkboxes o ...

Ignore error alerts during numpy array calculations

Is it possible to use "try-except" to handle errors in order to insert np.nan into the result array? For example: import numpy as np a = np.array([1,1]) b = np.array([1,0]) c = a/b When a "division by zero error" occurs, I would like to ignore it and ha ...

The API is now configured to provide a single result rather than returning multiple results in response to an 11ty/elevent

In my 11ty project (static site generator), I am fetching property data and then using it in a Promise.all call to: fetch all property images fetch tenancy application URLs After that, I combine these into one array named allData for my pages. The image ...

You can use jQuery AJAX to submit two forms' data simultaneously in just one submission

I am looking to submit two sets of form data with just one click. <form id="form1"> <input type="text" name="name"> <input type="submit" value="Submit"> </form> <form id=&quo ...

Unexpected behavior found in Vue 3 when using Proxy for reactivity in classes

I am facing an issue with a Class that has a proxy-based object. The set() method modifies another property of the same class, and everything runs smoothly when the code is executed in JS/TS. class Form { errors = [] values = {} constructor(value ...

Tips for eliminating Ref upon exiting the screen on React / React Native?

When navigating back in React / React Native, I am encountering keyboard flickering caused by the presence of Ref on the screen. I would like to remove it before leaving the screen. The code snippet I am using is as follows: // To focus on the input fie ...