What is the Best Method for Dividing an Array in Typescript?

I'm working on a project using Angular2, and I have a collection of parties.

const PARTIES: Party[] = [
  { id: 1, title: "Main Event", description: "The biggest, most extravagant event in the last 10,000,000 years." },
  { id: 2, title: "Secondary Event", description: "The not as biggest, less extravagant event in the last 10,000,000 years." },
  { id: 3, title: "Another Event", description: "N/A" },
  { id: 4, title: "Another Event", description: "N/A" },
  { id: 5, title: "Another Event", description: "N/A" },
  { id: 6, title: "Another Event", description: "N/A" },
  { id: 7, title: "Another Event", description: "N/A" },
  { id: 8, title: "Another Event", description: "N/A" },
  { id: 9, title: "Another Event", description: "N/A" },
  { id: 10, title: "Another Event", description: "N/A" }
];

I want to divide this array into groups of 3 while keeping the original intact.

In regular JavaScript, I would do something like this:

var chunk_size = 3;
var arr = PARTIES;
var groups = arr.map(function(e,i){
    return i%chunk_size===0 ? arr.slice(i,i+chunk_size) : null;
})
.filter(function(e){ return e; });
PARTIES = groups

However, I am using TypeScript. Is it possible to achieve the same segmentation using TypeScript?

Answer №1

Your JS code needs some fixing:

var chunk_size = 3;
var arr = PARTIES;
var groups = arr.map(function(e,i){
    return i%chunk_size===0 ? arr.slice(i,i+chunk_size) : null;
})
.filter(function(e){ return e; });
PARTIES = groups

This code is not correct, but if it were in TypeScript, it would work fine because JavaScript is a subset of TypeScript https://basarat.gitbooks.io/typescript/content/docs/why-typescript.html :)

Cleanup

Here's a fixed and functional sample:

const PARTIES = [
  { id: 1, title: "Main Event", description: "The biggest, most extravagant event in the last 10,000,000 years." },
  { id: 2, title: "Secondary Event", description: "The not as biggest, less extravagant event in the last 10,000,000 years." },
  { id: 3, title: "Another Event", description: "N/A" },
  { id: 4, title: "Another Event", description: "N/A" },
  { id: 5, title: "Another Event", description: "N/A" },
  { id: 6, title: "Another Event", description: "N/A" },
  { id: 7, title: "Another Event", description: "N/A" },
  { id: 8, title: "Another Event", description: "N/A" },
  { id: 9, title: "Another Event", description: "N/A" },
  { id: 10, title: "Another Event", description: "N/A" }
];

var chunk_size = 3;
const groups = PARTIES.map(function(e,i){
    return i%chunk_size===0 ? PARTIES.slice(i,i+chunk_size) : null;
})
.filter(x=>!!x)

console.log(groups);

A few points on the corrections:

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

"Is it possible to create a single-page website with a unique logo for each div

Is it possible to have a unique logo on each section of my single-page website? Each section has its own div. Check out my website at . Thank you in advance! ...

The data remains stagnant even after employing the onDataChange function in react native following the integration of a reusable component

My reusable Text input component is not working properly for validation. I am unable to retrieve the input value as it always shows null. This is how I am retrieving the username and password: <LoginTextBox placeholderName='Email& ...

How can I automatically copy a highlighted link in HTML?

I am attempting to implement a feature where users can click on a link and have it automatically copied. For example, I want it to appear like this: "UPI ID: david@okidfcbank". In this case, the link should be highlighted in blue. This is the code I have ...

Simple method for wrestling with objects in TypeScript HTTP POST responses

Can anyone help me understand how to extract information from an object received through an HTTP POST request? Below is the code I am using: this.http.post(url, user, httpOptions).subscribe(result => { console.log(result.status); }); The issue aris ...

The attempt to decode the string from POST using json_decode failed due to a hang-up in

I'm currently learning about PHP, JSON, and JavaScript. I am facing an issue with using the json_decode function in PHP after receiving a JSON string from JavaScript. I am able to save the JSON string to a file without any problem, but when I try to ...

Determine a value by incrementing a number in a loop

+---+---+---+ | 1 | 0 | 0 | +---+---+---+ | 2 | 1 | 0 | +---+---+---+ | 3 | 2 | 0 | +---+---+---+ | 4 | 0 | 1 | +---+---+---+ | 5 | 1 | 1 | +---+---+---+ | 6 | 2 | 1 | +---+---+---+ | 7 | 0 | 2 | +---+---+---+ | 8 | 1 | 2 | +---+---+---+ | 9 | 2 | 2 | +--- ...

Using AngularJS, REST API, SpringSecurity, and Hibernate in any software program

I am looking to create a web application using the following technologies: AngularJS, Spring Security, RestAPI, Hibernate Can anyone recommend or provide code for integrating these technologies together? ...

Navigate to all hyperlinks in browser without the use of jQuery - specifically for Firefox OS

I stumbled upon this interesting solution on a programming forum. I'm curious, how does this code work without relying on jquery? $('a[href^=http]').click(function(e){ e.preventDefault(); var activity = new MozActivity({ name: ...

Using an If Statement within a Foreach Loop

I am currently working on simplifying a PHP page and encountering some challenges that I need help with. My form collects user data, submits it to itself, validates the filled fields, and then saves the form contents to a MySQL database. The issue I' ...

Utilize Chrome storage instead of localstorage to generate Parse sessions

I'm currently developing a Chrome Extension that relies on Parse User sessions. Because localstorage is limited to specific domains, I am looking to utilize chrome.storage so the data can be accessed across any site. The existing Parse Javascript SDK ...

Why isn't my CSS transition animation working? Any suggestions on how to troubleshoot and resolve

I am looking to incorporate a transition animation when the image changes, but it seems that the transition is not working as intended. Can anyone provide guidance on how to make the transition style work correctly in this scenario? (Ideally, I would like ...

The access-control-allow-headers token is absent from the CORS header 'Access-Control-Allow-Headers' during the CORS preflight process

I am facing an issue with two VS projects: one has MVC5 controllers exposed, while the other is an Angular client. I need the Angular client to be able to query the controllers. I have done some research and attempted the following steps: I added the f ...

Insert a new item into an existing list using jQuery

I am looking to enhance user experience by allowing them to easily add multiple sets of inputs with just one click. I have been experimenting with jQuery in order to dynamically insert a new row of input fields after the initial set. My current approach i ...

"Unlocking the potential of Vue.js: Grabbing the object ID with a

I am encountering an issue with accessing the object ID when I click on the edit or delete buttons in my CRUD operation. The event.target is returning the values of the edit and delete buttons instead. This is what my HTML template looks like: <div ...

List of checkboxes that will not trigger the AJAX call if only one checkbox is selected

Apologies for the quick repost, but I have exhausted numerous options in the hopes of finding a solution. I am facing an issue with my jQuery/AJAX form where it creates a blank result when only one checkbox is selected. However, selecting two or more chec ...

Click event for jQuery horizontal accordion

I'm attempting to create a simple horizontal accordion-style element. My setup includes three 'banner' divs and three 'area' divs. Ideally, when I click on a banner, the corresponding area should animate - expanding in width to au ...

Testing Jasmine asynchronously with promise functionality

During my Jasmine testing with angular promises, a question arose regarding timing. I came across a post at Unit-test promise-based code in Angular, but I still need some clarification on how it all functions. The concern is that since the then method is ...

Tips for aligning a div within another div using ReactJs

I'm having trouble positioning the children div at the end of the parent div in my code using reactJs, NextJs, and styled-components. Here is the ReactJS code: <a href={links[indexImg]} target="_blank" > <Carousel image ...

Error: karma cannot locate the templateUrl for Angular component

I'm encountering some issues while running tests on angular directives with karma. The problem arises when the directive comes from a templateUrl and is not being translated properly. Here's my karma.conf.js configuration: 'use strict&apos ...

Personalized directive for HTTP validation, display dialog box upon detection of incomplete match

Looking to validate input against a server-side REST API and provide options for selection if invalid while typing. Already implemented in jQuery, now looking to implement in AngularJS. Would it be better as a custom directive or functions in the controll ...