Rearrange JavaScript Object in a Custom Sequence

Looking to filter a JSON Object (Array of Arrays) with a specific order requirement:

order: ['Hors','TTC','Total général', 'verger', ' Tra']

data = [[" Tra", "100 - 149 ch", "Total"]
[" Tra", "150 - 199 ch", "150 - 159 ch"]
[" Tra", "150 - 199 ch", "160 - 169 ch"]
[" Tra", "500 - 999 ch", "Total"]
[" Tra", "Total", ""]
["Comparable", "", ""]
["Hors", "", ""]
["TTC", "", ""]
["Total général", "", ""]
["vergers", "  1 - 49 ch", "20 - 29 ch"]
["vergers", "  1 - 49 ch", "30 - 39 ch"]
["vergers", "  1 - 49 ch", "40 - 49 ch"]
["vergers", " 50 - 99 ch", "70 - 79 ch"]]

Attempts using sort() method have not met the criteria due to spaces within strings:

data.sort(function (a, b) {
    return data.sort((a,b) => order.indexOf(a) - order.indexOf(b)) ;

});

Despite efforts, this approach did not yield the desired outcome, retaining the same Object structure.

Answer №1

If you wish to have all your data returned but organized in the same order as the array provided, you can utilize the filter function like so:

order= ['Hors','TTC','Total général', 'vergers', ' Tra']
const data = [ [" Tra", "100 - 149 ch", "Total"], [" Tra", "150 - 199 ch", "150 - 159 ch"], [" Tra", "150 - 199 ch", "160 - 169 ch"], [" Tra", "500 - 999 ch", "Total"], [" Tra", "Total", ""], ["Comparable", "", ""], ["Hors", "", ""], ["TTC", "", ""], ["Total général", "", ""], ["vergers", "  1 - 49 ch", "20 - 29 ch"], ["vergers", "  1 - 49 ch", "30 - 39 ch"], ["vergers", "  1 - 49 ch", "40 - 49 ch"], ["vergers", " 50 - 99 ch", "70 - 79 ch"] ]

function sort(order){
   result=[]
   order.forEach(el =>result.push(data.filter(o=>el==o[0])));
   result.unshift(data.filter(o=>!order.some(y=>y==o[0])))
  return result.flat()
}
console.log(sort(order))

If you are interested in filtering and sorting only the elements from the order array, you might want to consider this approach:

order= ['Hors','TTC','Total général', 'vergers', ' Tra']
const data = [ [" Tra", "100 - 149 ch", "Total"], [" Tra", "150 - 199 ch", "150 - 159 ch"], [" Tra", "150 - 199 ch", "160 - 169 ch"], [" Tra", "500 - 999 ch", "Total"], [" Tra", "Total", ""], ["Comparable", "", ""], ["Hors", "", ""], ["TTC", "", ""], ["Total général", "", ""], ["vergers", "  1 - 49 ch", "20 - 29 ch"], ["vergers", "  1 - 49 ch", "30 - 39 ch"], ["vergers", "  1 - 49 ch", "40 - 49 ch"], ["vergers", " 50 - 99 ch", "70 - 79 ch"] ]

function sort(order){
   result=[]
   order.forEach(el =>result.push(data.filter(o=>el==o[0]));
  return result.flat()
}
console.log(sort(order))

Answer №2

const information = [
    [" Purch", "100 - 149 ch", "Total"],
    [" Purch", "150 - 199 ch", "150 - 159 ch"],
    [" Purch", "150 - 199 ch", "160 - 169 ch"],
    [" Purch", "500 - 999 ch", "Total"],
    [" Purch", "Total", ""],
    ["Comparable", "", ""],
    ["Hors", "", ""],
    ["TTC", "", ""],
    ["Total général", "", ""],
    ["orchards", "  1 - 49 ch", "20 - 29 ch"],
    ["orchards", "  1 - 49 ch", "30 - 39 ch"],
    ["orchards", "  1 - 49 ch", "40 - 49 ch"],
    ["orchards", " 50 - 99 ch", "70 - 79 ch"]
  ]
  
  function rearrange(arr) {
    return arr.filter(ele => ["Hors","TTC", "Total général"].some(val => val === ele[0]))
      .concat(arr.filter(ele => ele[0] === "orchards"))
      .concat(arr.filter(ele => ele[0] === " Purch"))
  }
  
  console.log(rearrange(information));

Answer №3

If you are looking to arrange the arrays based on the first element, you can use this method:

(I corrected 'verger' to 'vergers'. I believe it was a typo)

var order = ['Hors','TTC','Total général', 'vergers', ' Tra']

var data = [
  [" Tra", "100 - 149 ch", "Total"],
  [" Tra", "150 - 199 ch", "150 - 159 ch"],
  [" Tra", "150 - 199 ch", "160 - 169 ch"],
  [" Tra", "500 - 999 ch", "Total"],
  [" Tra", "Total", ""],
  ["Comparable", "", ""],
  ["Hors", "", ""],
  ["TTC", "", ""],
  ["Total général", "", ""],
  ["vergers", "  1 - 49 ch", "20 - 29 ch"],
  ["vergers", "  1 - 49 ch", "30 - 39 ch"],
  ["vergers", "  1 - 49 ch", "40 - 49 ch"],
  ["vergers", " 50 - 99 ch", "70 - 79 ch"]
];

data.sort((a,b) => order.indexOf(a[0]) - order.indexOf(b[0])) ;

console.log(data)

If you wish to also eliminate non-matching elements:

var order = ['Hors','TTC','Total général', 'vergers', ' Tra']

var data = [
  [" Tra", "100 - 149 ch", "Total"],
  [" Tra", "150 - 199 ch", "150 - 159 ch"],
  [" Tra", "150 - 199 ch", "160 - 169 ch"],
  [" Tra", "500 - 999 ch", "Total"],
  [" Tra", "Total", ""],
  ["Comparable", "", ""],
  ["Hors", "", ""],
  ["TTC", "", ""],
  ["Total général", "", ""],
  ["vergers", "  1 - 49 ch", "20 - 29 ch"],
  ["vergers", "  1 - 49 ch", "30 - 39 ch"],
  ["vergers", "  1 - 49 ch", "40 - 49 ch"],
  ["vergers", " 50 - 99 ch", "70 - 79 ch"]
];

data = data
  .filter(x => order.indexOf(x[0]) > -1)
  .sort((a,b) => order.indexOf(a[0]) - order.indexOf(b[0]));

console.log(data)

Answer №4

To correctly compare arrays, use indexOf(a[0]) and indexOf(b[0]) instead of indexOf(a) and indexOf(b). This way, you are comparing the first element of each array rather than the entire array.

const order = ['Hors','TTC','Total général', 'vergers', ' Tra'];                
                                                                                
const data = [                                                                  
    [" Tra", "100 - 149 ch", "Total"],                                          
    [" Tra", "150 - 199 ch", "150 - 159 ch"],                                   
    [" Tra", "150 - 199 ch", "160 - 169 ch"],                                   
    [" Tra", "500 - 999 ch", "Total"],                                          
    [" Tra", "Total", ""],                                                      
    ["Comparable", "", ""],                                                     
    ["Hors", "", ""],                                                           
    ["TTC", "", ""],                                                            
    ["Total général", "", ""],                                                  
    ["vergers", "  1 - 49 ch", "20 - 29 ch"],                                   
    ["vergers", "  1 - 49 ch", "30 - 39 ch"],                                   
    ["vergers", "  1 - 49 ch", "40 - 49 ch"],                                   
    ["vergers", " 50 - 99 ch", "70 - 79 ch"],                                   
];                                                                              
                                                                                
    /* const weights = Object.fromEntries( */                                   
    /*     order.map((k,i)=>[k,i]) */                                           
    /* ); */                                                                    
    /* console.log(weights); */                                                 
                                                                                
function sortByOrder(data, order) {                                             
    const weight = Object.fromEntries(                                          
        // Pre-cache indexOf(...)                                               
        order.map((k,i)=>[k,i])                                                 
    );                                                                          
    return data.sort(                                                           
        ([a],[b])=>weight[a]-weight[b]                                          
    );                                                                          
};                                                                              
                                                                                
console.log(sortByOrder(data,order));                                           
                                                                                
// [ [ 'Hors', '', '' ],                                                        
//   [ 'TTC', '', '' ],                                                         
//   [ 'Total général', '', '' ],                                               
//   [ 'vergers', '  1 - 49 ch', '30 - 39 ch' ],                                
//   [ 'vergers', '  1 - 49 ch', '20 - 29 ch' ],                                
//   [ 'Comparable', '', '' ],                                                  
//   [ 'vergers', ' 50 - 99 ch', '70 - 79 ch' ],                                
//   [ 'vergers', '  1 - 49 ch', '40 - 49 ch' ],                                
//   [ ' Tra', '150 - 199 ch', '150 - 159 ch' ],                                
//   [ ' Tra', 'Total', '' ],                                                   
//   [ ' Tra', '500 - 999 ch', 'Total' ],                                       
//   [ ' Tra', '150 - 199 ch', '160 - 169 ch' ],                                
//   [ ' Tra', '100 - 149 ch', 'Total' ] ]  

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

The Firebase function that reloads the auth currentUser is not refreshing properly within a Vue component

My function for updating the profile URL using the reload method is not reflecting changes in my computed property. Computed Property computed: { photoUrl: function() { return firebase.auth().currentUser.photoURL; }, } Function onFileC ...

Sending data in chunks using Vue.js

I'm interested in sending the data in chunks. Currently, what I send to the server looks like this: for loop - 1, 2, 3. However, the server receives it asynchronously as 3, 1, 2 and I need it to be received synchronously in the order of my for loop: 1 ...

Tips for maintaining the InteractionCollector's presence even after a Discord.js bot reboot

One of the tasks my AI assistant handles is processing proposals submitted through Google Forms and transferring them to a designated channel where individuals can cast their votes by selecting either Yes or No using the corresponding MessageButton. Once ...

Verify if any choices are available before displaying the div block

I need to determine if there is a specific option selected in a dropdown menu, and then display a div if the option exists, otherwise hide it. I'm not just checking the currently selected option, but all available options. if (jQuery(".sd select opti ...

Assign JSON data to Tabbar in a Flutter app

I need help mapping a list of JSON objects to a tab bar, with the tab bar title being "JSON1". API response: "data": [{"JSON1": {"key1": "val1","key2": "val2"}}], Here is my code: List dataResponse = [{JSON1: {key1: val1, key2: val2}}]; TabBar( tabAlign ...

Guide on how to receive multiple responses from a single ajax request in PHP

I am in the process of developing a web application that includes a search feature. When a user enters a name to search for, I use an AJAX request to retrieve and display records related to that specific person. However, due to the extensive amount of info ...

View 360-degree panoramas on an iPad using the krpano HTML

I am currently experimenting with the KRPano HTML5 panorama viewer for a specific page on tablets/iPads. The flash viewer works seamlessly on desktops: embedpano({ swf: "/Files/Flash/krpano.swf", xml: "/Files/Flash/view.xml", target: "panview", id: "krpan ...

establishing a connection with the HTTP client server

try{ HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://nayyar.5gbfree.com/welcome.php"); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); H ...

Determine if the webpage is the sole tab open in the current window

How can I determine if the current web page tab is the only one open in the window? Despite searching on Google for about 20 minutes, I couldn't find any relevant information. I would like to achieve this without relying on add-ons or plugins, but if ...

Is it true that by utilizing Vue's v-for, every line of HTML code becomes a

I'm struggling to utilize v-for in order to create multiple div elements, but no matter how I attempt it (even trying to iterate over a list), the v-for doesn't seem to function properly and always turns the line into a comment when executed. No ...

Is it not possible to apply the .includes method on a string within a v-if directive while utilizing a computed property?

Problem I am facing an issue while trying to determine if a string contains a substring within the Vues v-if directive. The error message I receive is: TypeError: $options.language.includes is not a function The technologies I am using are Vue, Vuex, and ...

Permitting the inclusion of decimals in the isNaN function

My script currently has the capability to input a number in one textbox and calculate its equivalent in other textboxes. $("input[type=text]").keyup(function () { var number = parseFloat($(this).val()); var inc = parseFloat($(this).attr( ...

Retrieve all exports from a module within a single file using Typescript/Javascript ES6 through programmatic means

I aim to extract the types of all module exports by iterating through them. I believe that this information should be accessible during compile time export const a = 123; export const b = 321; // Is there a way to achieve something similar in TypeScript/ ...

Obtaining JSON data in an Angular service: A beginner's guide

My JSON file has the following structure: { "user": [ { "id": 0, "data": [ { "userName": "iheb", "useremail": "", "userPassword": "kkk" } ], "questionnaireListe": [ { ...

Issue: "StoreController Undefined" error in Python Flask + Angular application

In the python flask application that I have built with Angular JS for the front end, there are three main files. app.py import json import flask import numpy as np app = flask.Flask(__name__) @app.route("/") def index(): ...

Fade in text effect using jQuery on a Mac computer

Trying to create a smooth text fading effect across different browsers using jQuery. In the example below, you may notice that during the last part of the animation when the text fades in, the font weight suddenly increases causing a jerky/clunky appearan ...

Utilize select2 for dynamically loading an external html component

When the page is loaded, it includes another HTML page with a select element that I want to style using select2. The basic page structure looks like this: <select class="selectAddItem" id="selectAddItem" name="selectAddItem" style="width: 150px;" clas ...

Extracting information from a checkbox list displayed within an HTML table

I have a table with multiple rows and two columns in each row. The first column contains text, and the second column consists of checkboxes. While I was able to retrieve the values from the first column, I am struggling to fetch the values of the selected ...

What are the steps to accessing the scene, renderer, and camera objects in Forge Viewer v6 using TypeScript?

In the past, I could utilize code such as this: var container = viewer.canvas.parentElement; var renderer = viewer.impl.renderer(); var scene = viewer.impl.scene; To access Three.js objects in Forge Viewer. With version 6, how can I achieve the same usin ...

Put the JSON data into the database table

To add data to a MySQL table using a JSON string array in Postman, I have set up two tables in one database - one for questions and the other for answers. The goal is to insert both question and answer data into these tables using a POST request. Below is ...