Using a Javascript for loop to store results in a nested array

Is there a way to effectively extract specific data from a nested array and place it into a new nested array without just pushing all the data into one array?

var selection = [0,1,3,4];
var allProductData = [['Item1Sku','Item1Name', 'Item1Desc', 'Item1Price', 'Item1Available', 'Item1Margin'], ['Item2Sku','Item2Name', 'Item2Desc', 'Item2Price', 'Item2Available', 'Item2Margin'], ['Item3Sku','Item3Name', 'Item3Desc', 'Item3Price', 'Item3Available', 'Item3Margin']]
var selectedProductData = []

for(var apd=0; apd<allProductData.length; apd++) {
  for(var spd=0; spd<allProductData[apd].length; spd++) {
    for(var s=0; s<selection.length; s++) {
      if(allProductData[apd].indexOf(allProductData[apd][spd]) === selection[s]) {
        selectedProductData.push(allProductData[apd][spd])
      }
    }
  }
}
console.log(selectedProductData)

The current output:

[
  "Item1Sku","Item1Name","Item1Price","Item1Available",
  "Item2Sku","Item2Name","Item2Price","Item2Available",
  "Item3Sku","Item3Name","Item3Price","Item3Available"
]

I am aiming for:

[
  ["Item1Sku","Item1Name","Item1Price","Item1Available"],
  ["Item2Sku","Item2Name","Item2Price","Item2Available"],
  ["Item3Sku","Item3Name","Item3Price","Item3Available"]
]

If you have any advice on how to achieve this desired result, I would greatly appreciate it.

Answer №1

You have the option to associate the data with the values located at a specific index of your choosing.

const
    selection = [0, 1, 3, 4],
    allProductData = [['Item1Sku', 'Item1Name', 'Item1Desc', 'Item1Price', 'Item1Available', 'Item1Margin'], ['Item2Sku', 'Item2Name', 'Item2Desc', 'Item2Price', 'Item2Available', 'Item2Margin'], ['Item3Sku', 'Item3Name', 'Item3Desc', 'Item3Price', 'Item3Available', 'Item3Margin']],
    selectedProductData = allProductData.map(values => selection.map(i => values[i]));

console.log(selectedProductData);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

Implement Array.prototype.reduce to condense the array and verify if the index of each current element falls within the specified selection array; if yes, include it in the new array.

const selection = [0, 1, 3, 4];
const allProductData = [
  ['Item1Sku', 'Item1Name', 'Item1Desc', 'Item1Price', 'Item1Available', 'Item1Margin'],
  ['Item2Sku', 'Item2Name', 'Item2Desc', 'Item2Price', 'Item2Available', 'Item2Margin'],
  ['Item3Sku', 'Item3Name', 'Item3Desc', 'Item3Price', 'Item3Available', 'Item3Margin']
];

const selectedProductData = allProductData.reduce((acc, curr) => {
  const filtered = curr.filter((product, idx) => selection.includes(idx));

  if (filtered.length) {
    acc.push(filtered);
  }
  return acc;
}, []);

console.log(selectedProductData);

Answer №3

Consider using the for...of loop instead of i=0;i<x;i++ for better readability and smoother flow in your code.

You can also access each element's index within the initial loop without creating a separate selection array. This way, you can optimize your code by eliminating an extra loop.

var allProductData = [['Item1Sku', 'Item1Name', 'Item1Desc', 'Item1Price', 'Item1Available', 'Item1Margin'],['Item2Sku', 'Item2Name', 'Item2Desc', 'Item2Price', 'Item2Available', 'Item2Margin'],['Item3Sku', 'Item3Name', 'Item3Desc', 'Item3Price', 'Item3Available', 'Item3Margin']];
var selectedProductData = [];

for (let data of allProductData) {
  selectedProductData.push([data[0], data[1], data[3], data[4]]);
}

console.log(selectedProductData)

Answer №4

One efficient approach is to create a new array within the main for loop and append the desired results into that array first, then push the newly created array into the final result array:

var selection = [0,1,3,4];
var allProductData = [['Item1Sku','Item1Name', 'Item1Desc', 'Item1Price', 'Item1Available', 'Item1Margin'], ['Item2Sku','Item2Name', 'Item2Desc', 'Item2Price', 'Item2Available', 'Item2Margin'], ['Item3Sku','Item3Name', 'Item3Desc', 'Item3Price', 'Item3Available', 'Item3Margin']]
var selectedProductData = []

for(var apd=0; apd<allProductData.length; apd++) {
  var temp = []; // initialize a new array here
  for(var spd=0; spd<allProductData[apd].length; spd++) {
    for(var s=0; s<selection.length; s++) {
      if(allProductData[apd].indexOf(allProductData[apd][spd]) === selection[s]) {
        temp.push(allProductData[apd][spd]); // store the matching element 
      }
    }
  }
  selectedProductData.push(temp); // add the temporary array into the final result array
}
console.log(selectedProductData)

Answer №5

Implement array.map and array.filter to achieve the desired outcome.

var selection = [0,1,3,4];
var allProductData = [['Item1Sku','Item1Name', 'Item1Desc', 'Item1Price', 'Item1Available', 'Item1Margin'], ['Item2Sku','Item2Name', 'Item2Desc', 'Item2Price', 'Item2Available', 'Item2Margin'], ['Item3Sku','Item3Name', 'Item3Desc', 'Item3Price', 'Item3Available', 'Item3Margin']];

let result = allProductData.map(data => {
    return data.filter((el, ind) => selection.indexOf(ind)!=-1);
})

console.log(result);

Answer №6

Here is a code snippet that accomplishes the desired task. You can also check out the following resources:

let selection = [0,1,3,4];
let allProductData = [['Item1Sku','Item1Name', 'Item1Desc', 'Item1Price', 'Item1Available', 'Item1Margin'], ['Item2Sku','Item2Name', 'Item2Desc', 'Item2Price', 'Item2Available', 'Item2Margin'], ['Item3Sku','Item3Name', 'Ite...
console.log(filtered);

In the comments, there was discussion about the syntax below, specifically regarding the necessity for the callback function in filter() to return true. According to the official documentation from MDN:

The function should act as a predicate to evaluate each element of the array, returning true to keep the element and false otherwise.

let selection = [0,1,3,4];
let allProductData = [['Item1Sku','Item1Name', 'Item1Desc', 'Item1Price', 'Item1Available', 'Item1Margin'], ['Item2Sku','Item2Name', 'Item2Desc', 'Item2Price', 'Item2Available', 'Item2Margin'], ['Item3Sku','Item3Name', 'Item3Desc', 'Item3P...
console.log(filtered);

The above snippet could be revised as follows.

let selection = [0,1,3,4];
let allProductData = [['Item1Sku','Item1Name', 'Item1Desc', 'Item1Price', 'Item1Available', 'Item1Margin'], ['Item2Sku','Item2Name', 'Item2Desc', 'Item2Price', 'Item2Available', 'Item2Margin'], ['Item3Sku','Item3Name', 'Item3Desc', 'Item3Pr...
console.log(filtered);

There are additional examples provided that achieve the same outcome without errors. In all scenarios, what is returned by .filter() is logically true and meets the conditions specified in the callback function.

let selection = [0,1,3,4];
let allProductData = [[true,true, false, true, false, true], [true,true,true,true,true,true], [false,false,false,false,false,false]];
let filtered = allProductData.map(item =>
  item.filter((val,index) => selection.includes(index) && index > 3)
);
console.log(filtered);
filtered.forEach((item) => item.forEach((val) => console.log(typeof(val))));

Notice the variations in output based on the input values.

let selection = [0,1,3,4];
let allProductData = [[1,2,3,4,5,6], [6,5,4,3,2,1], [8,8,8,8,0,8]];
let filtered = allProductData.map(item =>
  item.filter((val,index) => selection.includes(index) && index > 3)
);
console.log(filtered);
filtered.forEach((item) => item.forEach((val) => console.log(typeof(val))));

Consider the impact of using different types of values, such as null.

let selection = [0,1,3,4];
let allProductData = [[null,null,null,null,null,null], [null,null,null,null,null,null], [null,null,null,null,null,null]];
let filtered = allProductData.map(item =>
  item.filter((val,index) => selection.includes(index) && index > 3)
);
console.log(filtered);
filtered.forEach((item) => item.forEach((val) => console.log(typeof(val))));

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

Utilizing jQuery to Perform Calculations with Objects

Can someone help me with a calculation issue? I need to calculate the number of adults based on a set price. The problem I'm facing is that when I change the selection in one of the dropdown menus, the calculation doesn't update and continues to ...

What could be causing the errors in my subscription function?

Working on an e-commerce website, I encountered errors in the "cartservice" specifically in the "checkoutFromCart()" function. The console displayed the following error: src/app/services/cart.service.ts:218:81 218 this.http.post(${this.serverUrl}ord ...

Unable to establish and subsequently change the state of the component

I have come across error messages similar to this one, but most of them were related to event binding. The error I am facing is: Cannot read property 'setState' of undefined I am getting this error message on this.setState(state => { Before ...

What is the correct way to express an object in an array?

I've encountered an issue: I'm working with an array called _daysConfig<DayConfig> When I manually populate it like this, everything functions correctly: _daysConfig: DayConfig[] = [ { date: new Date('Wed Jul 22 2020 21:06:00 GMT+02 ...

Implementing a pull-to-refresh feature in React Native using Redux

I need to implement pull to refresh functionality, but I'm unsure of what to call from _Refresh(). My actions, constants, and reducers are stored on another page. How can I trigger the API again? Thank you in advance for your assistance. class Homewo ...

Guide to customizing the Autocomplete jQuery plugin to mimic Google's result replacement feature

I have implemented the jQuery plugin Autocomplete like Google for two form fields - foo and bar (which is dependent on the value of foo): $(function() { $("#foo").autocomplete({ minLength: 3, limit: 5, source : [{ u ...

Experiencing difficulties managing NodeJS session

I've been attempting to integrate a login feature into my nodejs-based web application. const express = require('express'); const app = express(); const route = express.router; const sessions = require("client-sessions"); app.use(sessions ...

Issues encountered while integrating react-digraph with VueJS

My goal is to utilize react-digraph in building a UI tool for managing parent-child hierarchies sourced from a database. The graphs should be interactive, editable, and able to handle multiple parent-child relationships. After researching various librari ...

What could be causing the discord.js command handler to malfunction?

As I was working on developing a Discord Bot, I encountered an issue with the Command Handler while using a for loop. This is the code in Index.js: client.commands = new Collection(); const commandFiles = fs.readdirSync('./commands').filter(fil ...

Is it possible to enforce strict typing for a property within an object that is declared as type 'any'?

In my code, I am dealing with a parent object of type 'any' that remains constant and cannot be changed. Within this context, I need to define a property for the parent object, but no matter what I try, it always ends up being loosely typed as &a ...

What is the reason behind only receiving input for the second array when using gets() twice in a program to collect input for two separate arrays simultaneously?

There is an issue with the code snippet provided below. It captures user input twice and stores it in two separate arrays. However, when attempting to print these arrays using puts(array1); and puts(array2);, the same value is being displayed for both ar ...

What causes an ajax request to submit "none" as the value of a dom element?

Seeking assistance! I've encountered a frustrating issue with my simple input box in a form. I am attempting to send the value from this input box to Django using Ajax post, but keep encountering a 500 error that reads ValueError at /rest/ Cannot use ...

The jQuery script operates just one time

Recently, I encountered a small issue with my script. It only seems to work once - after that, I have to refresh the page in order to remove a favorite article (which the script is supposed to do). $("a.fav_no").on('click', function () { ...

Maintain the expanded menu even after selecting a sub-item using jQuery

After conducting a thorough search, I was unable to find exactly what I needed. I have successfully implemented cookies on my menu so that when the page is reloaded, it remembers which menus were open. However, I noticed that clicking on a sub-item of Hy ...

Implementing a custom arrow icon and adding functionality for closing on click in Kendo Multiselect

I'm looking to enhance the functionality of my Kendo Multiselect by giving it the appearance and behavior of a standard dropdown list. I'd like to include an arrow or triangle icon that toggles and closes the list when clicked. Can anyone provide ...

Learn the step-by-step process of dynamically adding elements to a JavaScript object in JSON structure

We are attempting to dynamically generate a JSON object using a for loop. The intended result should resemble the following: posJSON = [ { "position": [msg[0].Longitude, msg[0].Latitude], "radius": 0.05, "color": [255, 255, 0, ...

Utilizing Omit for the exclusion of nested properties within a TypeScript interface

One of the components in a library I am using is defined like this: export interface LogoBoxProps { img: React.ReactElement<HTMLImageElement>, srText?: string, href?: LinkProps['href'] } export type LogoBoxType = React.FC<React.HT ...

The jQuery scrollTop feature seems to be malfunctioning

My code is causing an error that I don't understand. Any help would be appreciated... I'm getting the following error message: Property does not exist on type '.js--section-plan'.ts(2339) when I hover over the offset() in vscode $(&apos ...

Displaying currency format in an input field using AngularJS filter

I'm currently dealing with an input field that looks like this: <input type="text" class="form-control pull-right" ng-model="ceremony.CeremonyFee | number:2"> Although it is displaying correctly, I've noticed that it's disabled. The ...

Transferring the control's identifier to JavaScript using ScriptControlDescriptor

In my CreateChildControls() method, I am creating a control: HtmlGenericControl mycontrol= HtmlGenericControl("li"); mycontrol.ID = "controlID"; controlId = mycontrol.ID; protected virtual IEnumerable<ScriptDescriptor> GetScriptDescriptors() { ...