Reducing an array group using index in JavaScript: A beginner's guide

Do you have coding questions?

Check out this sample array group:

myArray = { tab1 : [], tab2 : [], tab3 : [], tab4 : [] }

I'm looking to always retain the first tab (tab1) and an additional tab based on an index (ranging from 2 to 4)

For instance, if my index value is 2, I aim to keep tab2 resulting in :

myArray = { tab1 : [], tab2 : [] }

Your help is appreciated!

Answer №1

If you're looking for a different approach, here's an alternative suggestion.

Start by creating an array inside the function with the string tab1 and another key that you want to preserve as received parameters.

  1. Utilize Object.keys to list all properties in the Myarray object.

  2. Use Array.prototype.filter to select keys that are present in the allowed list.

  3. Apply Array.prototype.includes to ensure they exist.

  4. Lastly, use Array.prototype.reduce to construct a new object with only the permitted properties.

const myArray = {
  tab1: [],
  tab2: [],
  tab3: [],
  tab4: []
}

function keepTab(array, tab) {
  let allowed = ['tab1'];
  let addKey = 'tab' + tab;
  allowed.push(addKey);
  const filtered = Object.keys(array)
    .filter(key => allowed.includes(key))
    .reduce((obj, key) => {
      obj[key] = array[key];
      return obj;
    }, {});

  return filtered;
}

console.log(keepTab(myArray, 2));

Answer №2

If you want to achieve a similar result, consider using Array.prototype.reduce

Object.entries(myArray).reduce((acc, [key, value], index) => {
  // Determine whether it is the first element or the one to retain
  if (!index || index === indexToKeep) {
    acc[key] = value;
  }
  return acc;
}, {});

The function Object.entries(myArray) will convert your object into a 2D array of key / value pairs

[
  ['tab1', [/* Value of myArray.tab1 */]], 
  ['tab2', [/* Value of myArray.tab2 */]], 
  // etc...
]

By using reduce, we iterate through each index of the 2D array and generate an object with updated values after each iteration.

In this context, acc represents the current value of the object, while [key, value] denotes the key and value of the ongoing iteration.

Answer №3

Retrieve tab1, along with another tab identified by an index...

let someIndex = 3;
let myArray = { tab1 : ['1'], tab2 : ['2'], tab3 : ['3'], tab4 : ['4'] }

let key = `tab${someIndex}`;

let reducedArray = { tab1: myArray.tab1, [key]: myArray[key] };
console.log(reducedArray)

Answer №4

To improve your code, consider implementing boundary-checking logic.

const allTabs = { tab1: [1], tab2: [2], tab3: [3], tab4: [4] };

const getTabs = (id, { tab1, ...tabs }) => {
  if (id < 2 || id > Object.keys(tabs).length + 1) {
    throw Error(`Tab ID of ${id} is out of bounds!`);
  }
  
  const tabKey = `tab${id}`;
  return { tab1, [tabKey]: tabs[tabKey] };
}

console.log(JSON.stringify(getTabs(2, allTabs))); // { tab1 : [1], tab2 : [2] }
console.log(JSON.stringify(getTabs(3, allTabs))); // { tab1 : [1], tab3 : [3] }
console.log(JSON.stringify(getTabs(4, allTabs))); // { tab1 : [1], tab4 : [4] }

// Handling lower-bound
try { 
  getTabs(1, allTabs);
} catch (e) { 
  console.log(e.message); // Tab ID of 1 is out of bounds!
}

// Handling upper-bound
try { 
  getTabs(5, allTabs); 
} catch (e) { 
  console.log(e.message); // Tab ID of 5 is out of bounds! 
}
.as-console-wrapper { top: 0; max-height: 100% !important; }

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

Incorporate Vuetify's v-stepper seamlessly with Vue router for dynamic functionality

Seeking assistance in integrating vuetify's v-stepper with vue router. Specific requirements include: Assigning each step its own route (e.g. /myform/step1, /myform/step2, /myform/step3, etc) Creating components for each step that are dynamically lo ...

"Exploring the Intersection of Meteor, NPM Packages, and Fiber Callbacks

I am currently utilizing request and cheerio to extract specific content, particularly a quote, from a website. Here is the code snippet ( server.js ) : q = new Mongo.Collection('quotelist'); postList = new Mongo.Collection('quotes&apos ...

Utilizing props for toggling the navigation list, incorporating nested arrays or objects

My issue involves two components that are loading data. I want the links to be output like this: group1 linka linkb However, they are currently displaying like this: group1 linka group1 linkb I believe the problem lies in how I am handling the ...

How to set cells to plain text in google sheets

I've been grappling with a formatting issue that I'm hoping someone can assist me with. In my script, there's a point where I need to combine the date value (e.g., 11/20/2020) from one column with the time (3:00 PM) from another column. This ...

Leveraging the power of Notepad++

When I attempt to use Notepad++ for Javascript, it isn't functioning as expected. Instead of displaying the proper outcome on the web page, all I see is a jumbled mess. Currently, I am using version 6.6.7 of Notepad++. Here's my process: Typ ...

Is there a way to trigger the bootstrap datetimepicker when a custom button is clicked, while also storing the selected value in a hidden textbox

When the ADD button is clicked, a datetimepicker should open. After selecting a value from the datetimepicker, it should be saved in the textbox with ID #myTextBox. <div> <input id="myTextBox" type="text" ng-model="c" data-provide="datepicker ...

Differences between angular.isDefined() and obj.hasOwnProperty()

When working with angular.js, how should I handle objects that may or may not have a status? What are the pros and cons of using angular.isDefined() versus item.hasOwnProperty() in this scenario? var checkStatus = function(item){ if(angular.isDefine ...

What is the best way to design a dynamic menu using HTML, CSS, and jQuery, where each li element gradually disappears?

Consider this menu structure: <ul class="main-menu"> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> <li>6</li> </ul> My task is to dynamically hide th ...

Ways to adjust the position of a DIV based on its index value

I'm currently working on a unique project that involves creating a triangular grid using HTML and CSS. The challenge I am facing is offsetting each triangle in the grid to the left by increasing amounts so they fit seamlessly next to one another. Righ ...

How do I retrieve the content within this HTML element using JavaScript based on its ID?

Is there a way to extract the string from this specific HTML element using JavaScript? The element has an id of recItemString_GPLA\|input, and within it, there is a string containing "qty" that I need to retrieve. Upon inspection of the element, the f ...

Animating color on a JSON model when loaded in three.js

Can you animate the colors of a loaded JSON model in three.js? In my code, I used the ObjectLoader() to render the model. Now, I want to be able to animate the color of the model after it's been loaded. var objectLoader = new THREE.ObjectLoa ...

jQuery - class remains unchanged on second click event

Operations: Upon clicking on an element with the class thumb_like or thumb_unlike, a like will be added or removed for the image using a POST request. The element with the class thumb_count will increase or decrease based on user actions. For example, lik ...

Troubleshooting Vue.js: Overutilization of EventBus causing repeated function calls

I'm in the process of implementing an 'undo delete' feature. To achieve this, I am utilizing an Event Bus to broadcast an event to two separate components as shown below: Undo.vue: EventBus.$emit(`confirm-delete-${this.category}`, this.item ...

Display the array in the Vue view section without using curly braces

I am trying to display the following array in the view section without braces and quotations. Currently, it is showing with exact array containing braces and quotations. Array ["WHATSAPP", "2G", "CLIQ"] Code <v-col cols=& ...

Run JavaScript code last before page unloads

Two pages are involved in this process. On the first page, there is a form that the user completes and then clicks on the submit button. After that, the code for the first page unloads, and the user is redirected to the second page. Actual Issue A loadin ...

The presence of ng-show dynamically adjusts the minimum height of a div element

I am encountering an issue with a div that has the class of wrapper. Inside this div, there is a parent div with the class of content-wrapper. The wrapper div includes a conditional directive ng-show which toggles between displaying or hiding its content. ...

The data seems to have disappeared from the HTTP requests in my Express and Mongoose project

I'm currently working on some files for a recipe app project. One of the files is recipe.js, where I have defined the Mongoose Schema for recipes and comments. The code snippet from the file looks like this: const express = require('express&apos ...

Retrieving ng-pattern as a variable from a service

Hey there! I'm currently working on an application that requires extensive form validation across multiple pages. To streamline this process, I am attempting to extract validation patterns from a service used among the controllers. However, I've ...

Failure to deliver messages through socket.emit

Check out the following JavaScript code snippet: `var express = require('express'); var app = express(); var http = require('http').Server(app); var path = require("path"); var io = require('socket.io')(http); app.get(&apos ...

Tips for incorporating a Python script into a online project

I've been working on a Python code that detects faces and eyes using face recognition. When the code runs in PyCharm, it displays a camera window. Now I'm trying to figure out how to integrate this window into a webpage project written in HTML, C ...