Arranging items by their values while appending them to an array using lodash's find method

When using an API, I receive an object called 'results' which contains other objects of type article or detail.

Each result (article or detail) includes its own results object with different pages of that type.

My goal is to organize these results in an array named 'pages' where all the articles come first followed by all the details.

The reason for sorting them in the array is because I need to prioritize displaying the articles before the detail pages on the frontend.

var pages = [];

_.find(results, function(r) {
    if(r.type === 'article') {
        _.forEach(r.results, function(p) {
            p.type = 'article';
            pages.push(r);
        });
    } else if(r.app === 'detail') {
        _.forEach(r.results, function(p) {
            p.type = 'detail';
            pages.push(p);
        });
    }
});

I attempted to achieve this using Lodash find, but I still encounter issues with the display order on the frontend, where the details sometimes appear after the articles.

It's important to note that the API can return combinations like {detail}, {article} or even {detail}, {article}, {detail}, {article}.

Sample data:

results: [
    {
        type: 'article',
        results: {
            {
                title: '',
                body: '',
                ...
            },
            ...
        }
    },
    {
        type: 'detail',
        results: {
            {
                title: '',
                body: '',
                ...
            },
            ...
        }
    },
    ...
]

Answer №1

We came to a conclusion after a lengthy discussion:

var sorted;
var articles = [];
var details = [];

var source = [{
  app: "article",
  results: [
    { title: "a" },
    { title: "b" },
    { title: "c" }
  ]
}, {
  app: "detail",
  results: [
    { title: "d" },
    { title: "e" },
    { title: "f" }
  ]
}, {
  app: "article",
  results: [
    { title: "g" },
    { title: "h" },
    { title: "i" }
  ]
}];

for (var i = 0; i < source.length; i++) {
  switch (source[i].app) {
    case "article": articles = articles.concat(source[i].results); break;
    case "detail": details = details.concat(source[i].results); break;
  }
}

sorted = articles.concat(details);
console.log("articles =", JSON.stringify(articles));
console.log("details =", JSON.stringify(details));
console.log("sorted =", JSON.stringify(sorted));
console.log("source =", JSON.stringify(source));

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

Transforming data into JSON using jQuery through iteration

I'm looking to loop through a JSON object that doesn't have explicit keys for its child arrays. Although I can access them directly by providing the key name, I want the code to dynamically extrapolate and display these child elements of the arra ...

Properly rendering the "created_at" field in a Vue.js component

Currently, I am working on displaying the "created_at" field from my database by utilizing Laravel as the backend app and Vuejs as the frontend application. At this moment, what is being displayed is: Time: { "created_at": "2018-02-22 14:14:30" } Howeve ...

Guide to integrating Bootstrap-Vue / Vue 2 with Vite

In the process of migrating my project from webpacker to vite, I encountered some Bootstrap Vue issues such as Multiple instances of Vue detected and $attr and $listeners is readonly, which are detailed in BootstrapVue's documentation here Previously ...

What impact does setting a variable equal to itself within a Dom Object have?

Within my code example, I encountered an issue with image sources and hrefs in a HTML String named tinymceToHTML. When downloading this html String, the paths were set incorrectly. The original image sources appeared as "/file/:id" in the String. However, ...

Rename the last key of an array in PHP

Is there a way for me to update the last key in an array? I attempted to achieve this using the following function that I created: function updateLastKey($newKey){ $arr = $_SESSION['files']; $oldKey = array_pop(array_keys($arr)); $ar ...

I am facing an issue with my PHP code where it is unable to retrieve and display data from MySQL by using the array

I'm new to working with JSON and I'm facing an issue where the code that displays the description (which is of type medium text) does not show anything in the browser, while the title with type: varchar 100 displays correctly. Here's my cod ...

Using a responsive menu (mmenu) can lead to an increase in Cumulative Layout

I've implemented mmenu as a responsive menu on my website. Recently, I discovered errors in Google's search console related to high CLS (Cumulative Layout Shift). Upon further investigation, I noticed that when loading my page in "slow" mode for ...

"Learn how to capture the complete URL and seamlessly transfer it to another JavaScript page using Node.js and Express.js

Is there a way to access the token variable in another page (api.js)? I need to use it in my index.js. var express = require('express'); var router = express.Router(); router.get('/', function(req, res ...

What is the best way to restrict input to only numbers and letters in Vue Js?

I only want the field name to accept numbers and letters, while the field number should only allow numbers. How can I achieve this? Where can I find documentation that explains it clearly? const app = new Vue({ el: '#app', data: { nam ...

Angular and Ionic Framework Highchart: Troubleshooting the Issue

I am trying to create a graph on my web application. However, I am struggling to understand how to integrate Angular with Highcharts. I am utilizing the highcharts-ng library from github.com/pablojim and the Ionic framework from ionicframework.com. I be ...

When it comes to JavaScript, the evaluation order of arguments and delayed evaluation play a crucial

Assuming function( arg1, arg2 ), is it true that arg1 will always evaluate before arg2 (unlike traditional C)? Is there a way to create a function where arguments are not evaluated immediately, but only on demand? For instance, in if( cond1 || cond2 ), c ...

Retrieve JSON data with Bootstrap Typeahead for both ID and Value

To enable autocomplete for the typeahead feature, I want it to work specifically with the name field. When an item is clicked, I need it to collect the corresponding id value. $('.autocomplete').typeahead({ source: function (query, process) ...

Combine various 2D numpy arrays to create a single 3D numpy array

I am working on a project where I need to combine multiple 2-D numpy arrays into a single 3-D numpy array and then save it as a compressed file in a specific directory for future use. As I iterate through a list, I compute forecasts for different hazards. ...

How to use return type arrays in JQuery

I am trying to make an ajax request in a Codeigniter function, and I am currently using the code echo json_encode($array) to echo the result array. My goal is to retrieve this return value as an array in the ajax call, which I plan to use in a chart (speci ...

The process of deep copying a Javascript object is not functioning properly within the Vue.js framework

When passing a clone of an object from a parent component to a child component using props, I encounter an issue where changing the value of the status property in the parent component's object also updates the value in the "cloned" object within the ...

Organizing a collection of objects in MongoDB for optimal efficiency

In my MongoDB collection, there is a document structured like this: { "_id": "63269e0f85bfd011e989d0f7", "name": "Aravind Krishna", "mobile": 7309454620, "email": "<a href="/cdn-cg ...

Having trouble with Vuetify's 'text-wrap' class not functioning properly for wrapping text to the next line? Find out

I'm encountering an issue where words get cut off on my cards and are moved to a new line. Here is an image showing the problem: https://i.sstatic.net/9mWbx.png I attempted to resolve this issue by using the class="text-wrap", but it did no ...

What steps should I take to fix the error message "Uncaught TypeError: Class constructor m must be called with 'new'" that occurs while attempting to access a polymer v2.0 application?

Is there a way to resolve this error that occurs when attempting to open a Polymer v2.0 app on Safari in iOS? Uncaught TypeError: Class constructor m cannot be invoked without 'new' from custom-elements-es5-adaptor. The Polymer v2.0 starter k ...

What happens when ES6 async/await interacts with Observables and streams during failures?

Recently, I attempted to reproduce this code from a GitHub repository (link provided). It worked as intended, but I encountered an issue with unhandled promise warnings. Where should I place the catch statement in a situation like this, if necessary? Are ...

Decode JSON data stored in a multi-dimensional array from a database

Within my database, there is a JSON structure stored in a column labeled 'price' with the data type of 'text'. { "desks": { "Dedicated Desk": "$400 mo" }, "private offices": { "1 Person": "$550 mo", "2 Person": "$1100 ...