Displaying a JavaScript array containing multiple arrays

I have a collection of arrays, each containing a set of list items, which I am displaying using console.log(jobsList);. The output looks like this:

The variable jobsList is generated by adding arrays created inside a for loop like this:

for (var i=0; i < teamList.length; i++ ) {
  jobDirectory.push(newJob);
} 
jobsList.push(jobDirectory);

We then arrange the arrays by their length in the following way:

jobsList.sort(function(a,b){
  return a.length < b.length;
});

I want to display each array within an unordered list. The expected output should be as follows:

<h3></h3><ul>//insert list items here</ul>

This process will be repeated for each top-level array.

$('.row').append(jobsList); is causing an error. How can I display all the arrays within an unordered list as described above?

Answer №1

Here's a solution for you:

for (var i in jobsList)
    $('.row').append($('<ul />').append(jobsList[i]));

The issue with your code is that jobsList is not a simple array of elements, but actually an array of arrays of elements. By iterating through each array of elements, you can add them one by one to the DOM.

Answer №2

Combine forEach and join in the following manner.

itemsArray.forEach(function(item){

   $(".section").append("<div>"+item.join("")+"</div>");

});

Make sure that section refers to the class of the parent container of div. If there is no parent container for div, you can use main instead.

Answer №3

To implement the functionality, we recommend using the code snippet provided below:

$.each(jobsList, function () {
    var $list = $('<ul/>');
    var $row = $('.row');

    $.each(this, function () {
        $list.append($(this));
    });

    $row.append('<h3>some title</h3>')
    $row.append($list);
});

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

Guide to enclosing selected text within a span tag and positioning a div in relation to it using JavaScript

My main objective is to enable the user to: highlight text within a paragraph enclose the highlighted text in a span element add an action button or div at the end of the selected text for further interaction Here's the code I've worked on so ...

How to output a string in jQuery if it includes a certain character?

I need to extract all strings that include a specific word within them, like this: <div> <div> <span> <h3>In Paris (Mark Bartels) worked for about 50 years.</h3> </span> </div> ...

How to utilize jQuery to replace the first occurrence of a specific

Suppose I have an array structured like this: var acronyms = {<br> 'NAS': 'Nunc ac sagittis',<br> 'MTCP': 'Morbi tempor congue porta'<br> }; My goal is to locate the first occurrence ...

How can I stop json_encode() from including the entire page in the JSON response when submitting a form to the same PHP script?

I only have a single index.php file in my project. I am aware that it's recommended to separate the logic from the view and use different files for PHP, JS, and HTML. This is just a test: <?php if($_SERVER["REQUEST_METHOD"] == "P ...

Running Angular without dependencies causes it to malfunction

I recently ventured into the world of AngularJS and started by creating a module without any services or factories. Everything was running smoothly until I decided to introduce services and factories into my code. Suddenly, things stopped working. Here is ...

Sending two objects back in res.send() in an API: A step-by-step guide

I've got an API that looks like this router.get('/exist', async (req, res) => { try { const { user: { _id: userId } } = req; const user = await User.findById(userId); const profile = await Profile.findById(user.profile, &apo ...

The current context for type 'this' cannot be assigned to the method's 'this' of type '...'

Currently, I am in the process of defining type definitions (.d.ts) for a JavaScript library. In this specific library, one of the methods accepts an object of functions as input, internally utilizes Function.prototype.bind on each function, and then expos ...

Unable to capture HTML form input in $_POST[]

I've encountered an unusual issue while transferring data from an email form (HTML5) to ajax/JSON and receiving false in order to prevent redirection to the php script after pressing the submit button. When I include commas between each data paramete ...

Prevent mobile users from entering text with Material UI Autocomplete on keyboard

Currently, I am utilizing the Material UI Autocomplete component for multi-select functionality. Although it functions perfectly on desktop, I want to prevent keyboard input on mobile devices and only allow touch selection. Essentially, I do not want the v ...

Tips for enabling TypeScript's static typings to function during runtime

function multiply(num: number): number { console.log(num * 10) // NaN return num * 10 } multiply("not-a-number") // result == NaN When attempting to call the function above with a hardcoded invalid argument type, TypeScript correctly identifies and w ...

Error encountered when attempting to upload image on Twitter: missing media parameter

According to the latest Twitter media upload API documentation, it is recommended to first utilize either POST multipart/form-data or base64 encoded files when interacting with . However, encountering an error with code 38 stating "media parameter is mi ...

Classic ASP offers a feature that allows users to select all checkboxes at once

I'm looking to create a functionality where there is a 'Select all' checkbox along with individual checkboxes for each database record. Is it possible to use JavaScript to ensure that when the 'Select all' checkbox is checked, all ...

Invoking Ajax within a for loop

for (var i = 0; i < 5; i++) { using (x = new XMLHttpRequest()) sendRequest("GET","d.php?id=" + i), checkResponse(null), updateStatus = function() { if (x.state == 4 && x.responseCode == 200) notifyUser(i); } } My goal now is to e ...

Leveraging JSON to access arrays in React

In my current structure, I have: const [res, setRes] = useState({ question: "", option: [, , , ,], answer: 0, }); I am looking to update the values in the option array based on their indices. For example, setting option[3] to 2 ...

Effective ways to resolve the ajax problem of not appearing in the console

I am facing an issue with my simple ajax call in a Java spring boot application. The call is made to a controller method and the returned value should be displayed in the front-end console. However, after running the code, it shows a status of 400 but noth ...

Using Three.js to create a distorted texture video effect

Check out the example linked here for reference: In this particular project, there are two cylinders involved - an outer cylinder with an image texture and an inner cylinder with a video texture. Once the second cylinder is created and added to the scene, ...

Retrieve the values of elements

Is there a reliable way to retrieve an element's clientWidth and scrollWidth? I've tried using getCssValue, but it doesn't seem to work. $('.grid-header-col .title').getCssValue('scrollWidth') ...

Automating the process of transferring passwords from Chrome Password Manager to a Chrome Extension

Embarking on my first chrome extension journey, I have been developing a password manager app that offers enhanced functionalities beyond the default chrome password manager. A recent request from a client has come in, asking me to gather all passwords fr ...

Currently trapped within the confines of a Next.js 13 application directory, grappling with the implementation of a

I need to figure out how to export a variable from one component to layout.tsx in such a way that it is not exported as a function, which is currently causing the conditional check in the class name to always be true. Below is the code snippet: // File w ...

The error message "TypeError: undefined is not an object (evaluating '_reactNative.Stylesheet.create')" occurred in a React Native environment

I've been working on a project in React Native and have successfully installed all the necessary dependencies. However, upon running the code, I encounter the following error message: TypeError: undefined is not an object (evaluating '_reactNativ ...