Combining multiple arrays housed within a single variable

My function retrieves information from multiple APIs with callbacks to one variable (results):

function combineObjs(callback) {  
    function partialResult(results) {
        callback(results);
    };        
    searchFlickr.searchFlickr(searchTerm, searchCount, searchPage, partialResult);
    searchUnsplash.searchUnsplash(searchTerm, searchCount, searchPage, partialResult);
}

combineObjs( function(results) {
    console.log(results)
});

Although the data retrieval process seems to be effective, I encounter an issue when requesting 2 results from each source. The returned data appears as follows:

[ { id: 'flkr-13545844805',
    link: 'https://www.flickr.com/photos/28596055@N02/13545844805' },
  { id: 'flkr-3474831728',
    link: 'https://www.flickr.com/photos/9848951@N06/3474831728' } ]
[ { id: 'us-fRPxHaHwWwk',
    link: 'https://unsplash.com/photos/fRPxHaHwWwk' },
  { id: 'us-JXy99waA3Fo',
    link: 'https://unsplash.com/photos/JXy99waA3Fo' } ]

I have researched merging arrays in JavaScript, but the information I found pertains to merging separate arrays, requiring the naming of at least 2 arrays to push one into another. In my case, since I only have one array, those methods do not apply.

I have also attempted using a forEach loop to separate each section enclosed in curly braces, but then I face the challenge of comma separation before adding them to another array. I am uncertain about the best approach in this situation. Thank you in advance for any assistance.

Answer №1

To address your question, one possible solution is to utilize Array.prototype.reduce.

const nestedArray = [["x","y"], ["z","w"]];

const flattenedArray = nestedArray.reduce(function(flattened_array, current){
    if(Array.isArray(current)) {
        return [...flattened_array, ...current];
     } else {
         return [...flattened_array, current];
     }
},[]); //["x","y","z","w"]

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

Include a fresh attribute in the current response structure within OpenAPI 3.0.x

I have four paths a, b, c, and d. Each path has the same properties and schemas. However, there is a new requirement where paths c and d will have changes in the property called rex. It is crucial to ensure proper positioning for this update. How can I ach ...

Find the Time Difference in IST using JavaScript

Is there a way to calculate the time difference between two different time zones in javascript? var startTime = doc.data().startTime; output: Fri Dec 06 2019 19:00:00 GMT+0530 (India Standard Time) var currentTime = new Date(Date.now()).toString(); outpu ...

What is the best way to fetch the class name of an element in JSDOM?

In my current project, I am facing a challenge with extracting the className of an element using JSDOM. Despite being able to locate the element successfully, I have been unable to find any relevant examples or documentation on how to retrieve the classN ...

Having trouble importing Bootstrap into Next.js? It seems like the issue may be related to the

I am currently facing an issue with importing bootstrap 5.3.2 (not react-bootstrap) into my NextJS 14.1.0 project that utilizes the new App Router. My goal is to strategically utilize individual Bootstrap components (not through data-attrs). I managed to ...

When dynamically adding input fields in Bootstrap, there is a smaller gap between inline inputs

When adding a new list item dynamically in a modal using jQuery append, the spacing in the first li element seems to have a larger gap between the input fields compared to the rest that are added later. Even after checking the developer tools and confirmin ...

Achieving dynamic height in a parent div with a sticky header using mui-datatables

Here are the settings I've configured for my mui-datatables: const options = { responsive: "standard", pagination: false, tableBodyHeight: '80vh', }; return ( <MUIDataTable title={"ACME Employee ...

Custom variables can be passed to subscription buttons through Paypal

I am currently working on finding a solution to passing custom variables when applying for a subscription for my created web service. The code on the front end that I have implemented so far is as follows: const createSubscription = (data, actions) => { ...

Generate menu options in real-time

I have developed a React single page application using the NASA Picture of the Day API. I am looking to incorporate a drawer feature that displays a history of previously shown images, but only showing their dates. However, I am unsure of how to dynamical ...

Assigning an array of objects within an AJAX request

I have a MediaObject object that includes: a Media object an array and a function called getMedia() When attempting to create a Media object and push it into the array inside the getMedia function after making an AJAX call, I encountered issues referenc ...

Tips for successfully implementing a basic JQuery code in Internet Explorer

Having trouble getting this to work on my website, especially in Internet Explorer. Check it out here: http://jsfiddle.net/b43hj/24/ Any tips on how to make it compatible with all browsers? Thank you edit - I've only used the code from the jsfidd ...

I am interested in delivering a blended, divided response containing JSON and a string using Express

I am currently in the process of integrating ChatGPT into my Node/Express project and I have a specific requirement. I would like to initially send some metadata in JSON format to the client before streaming the response from ChatGPT as it comes in. Every ...

Tips for enabling/disabling a Chrome extension through the utilization of local storage in the background page

Even after reading numerous answers on similar questions, I am still facing some difficulties. My goal is to allow the user to disable my chrome extension by simply clicking on the icon at any time. The extension is designed to run once on every page load, ...

Enhancing a primary JSON structure by appending information to a nested object

Imagine having a list of JSON objects like the following: list = [{"Name": "NY", "Date": "12/2008", "features": [{"attributes": {"OID": 2, "Zone": "A"}, "geo": {"x": 10, "y": 20}}]},{"Name": "NY", "Date": "12/2008", "features": [{"attributes": {"OID": 3, ...

Stop the reloading of the parent page when the exit button is pressed on the popup screen

I have set up a modal popup that appears when a user clicks on a specific link. Inside the popup, I have included an exit button to close it. However, I am facing an issue where clicking on the exit button not only closes the popup but also reloads the par ...

Creating a List with Sublists that are displayed when hovering over the parent List is a key element of effective design

Hovering over 'View Rows' should open up both New Records and Old Records <div> <li>Add Rows</li> <li>DeleteRows</li> <li>View Rows <ul> <li>View New Records</li ...

Comparison of two variables in PHP using if-else statement

I currently have two variables: $arrAns, which contains the selected answers for a checkbox (e.g. 1, 2, 3), and $arr, which includes all the available options for the question (e.g. 1, 2, 3, 4, 5, 6). The code I'm using aims to compare if $arrAns == ...

Verify the position of the scrollbar without triggering any reflow

Here is a function I have: is_bottom: function() { if (settings.scrollBottomOffset === -1) { return false; } else { var scroll_height, scroll_top, height; scroll_height = ...

Choosing a particular svg path in d3.js using JSON attribute

Is it feasible to isolate just one of the SVG paths generated from a geoJSON file using D3? In my scenario, the paths represent different areas on a map. Users can pick an area from a dropdown menu. I aim to utilize the selected value from this list to pin ...

Mastering Vue.js: Leveraging v-model within a v-for loop and implementing watchers

After retrieving a list of debits and credits from a server using the fetch function, I store them in my Vue application: const myApp = Vue.createApp({ data(){ return{ debits:[], credits:[], //cut } }, me ...

Retrieving a channel using its unique ID and then sending a message directly into it

I am attempting to retrieve a channel by its ID and then send a message to it, but I keep encountering an error when running the code. ERROR: Error sending message to welcome channel.: TypeError: Cannot read properties of undefined (reading 'send&apos ...