Tips for organizing an array into three separate objects based on specific criteria

I have taken a word and split it into an array. Now, I am trying to divide that array into 3 separate objects like this:

Input:

var input = "7RD FLOOR, PAVE AVENUE BUILDING, DUNG STREET, 48 JUNG-GU, SEOUL 100-203" 

Desired Output:

let addresses = {
  address1: 7RD FLOOR, ... (must be less than 35 characters and words cannot be truncated)
  address2: BUILDING, DUNG STREET ... (must be less than 35 characters and words cannot be truncated)
  address3: 48 JUNG-GU ..... (the rest of the input array)
}

Current Attempt:

let addresses = response.address.split(" ");
var i;
var counterDump = 1;
addressSplitDump['address'+counterDump] = [];

for (i = 0; i < addresses.length; i++) {
    if (addressSplitDump['address'+counterDump].join(' ').length <= 35) {
        addressSplitDump['address'+counterDump].push(addresses[0]);
        let sliceAddress = addresses.shift();
    } else if (counterDump == 3 ) {
        addressSplitDump['address'+counterDump] = addresses;
    } else {
        counterDump++;
    }
}

Answer №1

Here is a method you can use to handle long input addresses:

const fullAddress = "7RD FLOOR, PAVE AVENUE BUILDING, DUNG STREET, 48 JUNG-GU, SEOUL 100-203";
const words = fullAddress.split(' ');
const formattedAddress = {
    address1: '',
    address2: '',
    address3: ''
};

words.forEach(word => {
    if (formattedAddress.address1.length + word.length < 35) 
        formattedAddress.address1 += formattedAddress.address1.length > 0 ? ` ${word}` : word;
    else if (formattedAddress.address2.length + word.length < 35) 
         formattedAddress.address2 += formattedAddress.address2.length > 0 ? ` ${word}` : word;
   else 
       formattedAddress.address3 += formattedAddress.address3.length > 0 ? ` ${word}` : word;
});

Answer №2

Give this a shot

let input = "7RD FLOOR, PAVE AVENUE BUILDING, DUNG STREET, 48 JUNG-GU, SEOUL 100-203 ADDED FOR TEST"

let addresses = {
    address1: '',
    address2: '',
    address3: ''
};

const words = input.split(' ');
words.forEach(word => {
    if (addresses.address1.length + word.length <= 35) 
        addresses.address1 = [addresses.address1, word].filter(Boolean).join(' ');
    else if (addresses.address2.length + word.length <= 35) 
        addresses.address2 = [addresses.address2, word].filter(Boolean).join(' ');
    else 
        addresses.address3 = [addresses.address3, word].filter(Boolean).join(' ');
});

console.log(addresses)

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

Execute the render function of the components that have been passed as

I've been grappling with a challenge lately - figuring out how to invoke a passed component's render function within another function. Let's say I have two functions named A and B: export const A = (value: any) => { return ( <div& ...

How to access the onchange text in a react-select search component

I'm currently working on implementing search select functionality in my webpage using the react-select-search npm package. This is my main component: import React, { Component } from "react"; import Task from "./task"; // Rest of ...

Exploring Flask: A Guide to Dynamically Choosing Image Paths in Templates

I have created a Flask application to display subsets of large image collections stored on my local NAS. These images are microscopy images of cultured cells used for scientific research. The app allows me to compare 10-20 images at a time and includes syn ...

Add elements to the array, extract elements from the array

tag, I am currently facing a challenge with transferring multiple attributes from SharePoint list items into an array (only selected items in a view) and then passing that array to a function where I can extract and use these attributes to create new list ...

Struggling to devise a for loop for a JavaScript-generated list

I'm attempting to loop the content of an H1 element through a list 10 times. I seem to have made a mistake in my code and would appreciate any guidance. var headOne = document.createElement("H1"); headOne.textContent = "Hello World"; document.body. ...

Disabling dates in the second datetimepicker depending on following days selected in the first one

I have implemented the bootstrap date picker and I am using two textboxes for searching by date range. I want the second textbox to display the days after the date selected in the first textbox. Any suggestions would be appreciated. Here is the HTML code: ...

Learn how to successfully import a webp image into a React TypeScript project

I have looked everywhere for the answer, but I can't seem to find it When trying to import a *.webp image in typescript, you need to create a declaration file, like declaration.d.ts The declaration file should contain something similar to the foll ...

Attempting to implement a smooth fade effect on my image carousel using React-Native

Struggling to animate this image carousel in reactNative and feeling lost. Despite reading the documentation on animations, I can't figure out how to implement it properly. My attempts keep resulting in errors. Any assistance would be greatly apprecia ...

Is it possible to link a Lua client with a Socket.io NodeJS server?

Currently, I have set up a Node JS server running socket.io that can successfully communicate with other clients using the socket.io-client package. My next step is to develop a Lua client that connects to my socket.io server and enables the sending and ...

It is possible that req.user may be undefined, especially when using express and passport.js

I am facing an issue with my Node.js TypeScript authentication system that utilizes passport. The problem arises when I attempt to access req.user in a specific route, resulting in the error message: Object is possibly 'undefined'. This behavio ...

Use JQuery to reverse the most recent button click

Here is the code snippet I am working with: <button class="btn">New York</button> <button class="btn">Amsterdam</button> <button class="btn">New Jersey</button> <button class="btn&qu ...

What causes the issue of JavaScript code not loading when injected into a Bootstrap 4 Modal?

I've created a JavaScript function that triggers the opening of a Bootstrap Modal Dialog: function displayModal(message, headerMessage, sticky, noFooter){ var modal = $('<div />', { class: 'modal fade hide ...

Link the requests together so that I can utilize the information gathered in the initial request for the subsequent one

Recently, I initiated a weather-app project as a way to enhance my React skills and learn about data fetching. import React, { Component } from 'react'; import './App.css'; import axios from 'axios'; class App extends Comp ...

Understanding the significance of an exclamation point preceding a period

Recently, I came across this code snippet: fixture.componentInstance.dataSource!.data = []; I am intrigued by the syntax dataSource!.data and would like to understand its significance. While familiar with using a question mark (?) before a dot (.) as in ...

Managing empty values within a two-dimensional array

Exploring an out of bounds check issue, I'm struggling with managing undefined values within a 2d array. My attempted solutions include verifying if both the column and row index are present using if(!arr[x][y]), checking if both are undefined with i ...

Creating dynamic bar chart visuals using Morris.js with JSON responses

Utilizing the morris.js library, I am extracting and plotting bar charts from data retrieved through a webservice. Issue: The format of my webservice URL is as follows: http://localhost:9999/hellowebservice/search?select=* I populate the select query ...

Bringing in States and Functions to a React Component

Is there a way to improve the organization of states and functions within a functional React Component? Here's my current code structure: import React from 'react' //more imports... const Dashboard = () => { const [] = useState() / ...

Form featuring a mandatory checkbox that must be selected in order to proceed; failure to do so will result in an

So here’s the situation: I have a form with a checkbox for agreeing to the terms of service, and I want to make sure it is checked before proceeding with the donation process. I only have the HTML code and no idea how to implement this functionality. Ide ...

Tips for transmitting one or multiple data using jquery.ajax

I found this code on stackoverflow and it is working well for uploading multiple files. However, I am facing an issue where I cannot send additional parameters along with the file upload. Despite trying various methods, I have been unsuccessful in sending ...

In the d.ts file, Typescript simply creates the line "export {};"

After executing the tsc command to compile my project into the dist directory, I noticed that typescript is generating an incorrect or empty d.ts file. Here is a snippet of my tsconfig.json: { "compilerOptions": { "module": " ...