How to find the higher numbers in an object in JavaScript?

I want to reach the higher numbers in an object.

let object1 = {
  a: 2,
  b: 2,
  c: 0,
  d: 3,
  e: 1,
  f: 1
}
// Need to get 2,2,3 above. The first 3 highest ones.
let object2 = {
  a: 7,
  b: 15,
  c: 1,
  d: 7,
  e: 4,
  f: 3
}
// 15,7,7 above.

But it is not like return > 1 because I cannot set an exact number; the object can be

let object1 = {
  a: 1,
  b: 1,
  c: 0,
  d: 2,
  e: 0,
  f: 0
}

I need to compare every single key with others so that I can find the higher numbers(for example the first 3 highest numbers) in the object.

I have tried it like keys.reduce but I could not reach out to a good solution.

React map library with editable polygon and get coords

I’m trying to make a map with a polygon that can be dragged and rotated and get the new position of that polygon. I tried different solutions for react but i did not manage to get the result that i want. Can you recommand or give an example of a library for react that can drag and rotate polygon?

Reading in a CSV file in Javascript produces bad result with some characters

I have an Excel file of which I have exported to a CSV file with UTF-8 encoding with BOM and am trying to read in Javascript according to

// Note I am using adoptOpenJdk to import JAva packets in Js.
var myReader = new java.util.Scanner(myObj, "UTF-8");
var data = myReader.nextLine();

but it produces incorrect results for characters such as ÅÄÖ (swedish letters). ä becomes Σ and ö becomes ÷.

Anyone have an idea what may be causing this?

How merge two arrays based on the key value matches

I am calling two API’s and I’m getting two responses with Array values I want to merge those two arrays based on the key-value(name) matches. can anyone help with this

response one

const items = [
    {
      date: "2016-01-11",
      data: [
        { name: "car", estimate: 1.94 },
        { name: "scooty", estimate: 0.73 },
        { name: "phone", estimate: 0.59 },
        { name: "laptop ", estimate: 0.59 }
      ]
    }
  ];

response 2

const value = [
    { name: "car", actual: 1.94 },
    { name: "scooty", actual: 0.73 },
    { name: "phone", actual: 0.19 },
    { name: "laptop ", actual: 1.79 }
  ];

I want to do like this can any help on this, please

const mergedArrays = [
    {
      date: "2016-01-11",
      data: [
        { name: "car", estimate: 1.94, actual: 1.94 },
        { name: "scooty", estimate: 0.73, actual: 0.73},
        { name: "phone", estimate: 0.93, actual: 0.19 },
        { name: "laptop ", estimate: 1.03, actual: 1.79 }
      ]
    }
  ];

turning multiple jQuery functions into one

i have a few jquery functions that i need to be turned into one.

// Show hidden paragraphs
$("#no678").click(function(){
    $("#imperial_number, #imperial_number2").hide();
});
$("#no678").click(function(){
    $("#metric_number, #metric_number2").show();
});

that’s what my code looks like and I have around 7 of these I need to be turned into one.

i have no clue how to move forward with this.

Why page reloaded after the table is created by JavaScript

There a dropdown list in <div> element.

When an item in the dropdown list is clicked, a table should be created.

However, it is found that the table is created, but the page seems refreshed.

How to keep the result ?

<style>
        #map {
            margin: 10px 10px;
            width:  560px;
            height: 560px;
            border: 1px solid #000000;
        }
        #dropdown_1 {
            margin: 10px 10px;
            position: absolute;
            top: 0;
            left: 600px;
            width:  50px;
            height: 10px;
           /*border: 1px solid #000000;*/
        }
        /* Dropdown Button */
        .dropbtn {
            background-color: #3498DB;
            color: white;
            padding: 16px;
            font-size: 16px;
            border: none;
            cursor: pointer;
        }
  
        /* Dropdown button on hover & focus */
        .dropbtn:hover, .dropbtn:focus {
            background-color: #2980B9;
        }
        
        /* The container <div> - needed to position the dropdown content */
        .dropdown {
            position: relative;
            display: inline-block;
        }
        
        /* Dropdown Content (Hidden by Default) */
        .dropdown-content {
            display: none;
            position: absolute;
            background-color: #f1f1f1;
            min-width: 160px;
            box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
            z-index: 1;
        }
        
        /* Links inside the dropdown */
        .dropdown-content a {
            color: black;
            padding: 12px 16px;
            text-decoration: none;
            display: block;
        }
        
        /* Change color of dropdown links on hover */
        .dropdown-content a:hover {background-color: #ddd}
        
        /* Show the dropdown menu (use JS to add this class to the .dropdown-content container when the user clicks on the dropdown button) */
        .show {display:block;}



</style>
<div id = "dropdown_1" class="dropdown">
        <button onclick="dropdown_toggle()" class="dropbtn">Dropdown</button>
        <div id="myDropdown" class="dropdown-content">
        </div>
</div>
<script src="myscripts.js">
</script>
<script>
    // document.addEventListener('keypress', logKey);
    set_drop_down_list();

    /* When the user clicks on the button, 
    toggle between hiding and showing the dropdown content */
    function dropdown_toggle() {
        document.getElementById("myDropdown").classList.toggle("show");
    }
// Close the dropdown if the user clicks outside of it
    window.onclick = function(event) {
    if (!event.target.matches('.dropbtn')) {
        var dropdowns = document.getElementsByClassName("dropdown-content");
        var i;
        for (i = 0; i < dropdowns.length; i++) {
            var openDropdown = dropdowns[i];
            if (openDropdown.classList.contains('show')) {
                openDropdown.classList.remove('show');
                // console.log('hit-hit');
                // creat_traffic_table();
            }
        }
    }
} 
</script>

In myscript.js :

function set_drop_down_list(){

  var c = document.getElementById("mycanvas");
  var ctx = c.getContext("2d");
  var img = new Image();        
  img.src = './pic/mps.png';
  img.onload = () => {ctx.drawImage(img, 0, 0);};
 

  var select = document.getElementById("myDropdown");
  var options = ["Ma Wan", "Kap Shui Mun", "North Fairway", "Ha Pang", "Fairway Junction"];

  for(var i = 0; i < options.length; i++) {
      var opt = options[i];
      var el = document.createElement("a");
      el.textContent = opt;
      el.value = opt;
      el.setAttribute("href", "");
      el.onclick = function(event) {
        creat_traffic_table();
      }
      select.appendChild(el);
  }   
 
}


function creat_traffic_table(){

  var myArray = [
    {'name':'Michael', 'age':'30', 'birthdate':'11/10/1989'},
    {'name':'Mila', 'age':'32', 'birthdate':'10/1/1989'},
    {'name':'Paul', 'age':'29', 'birthdate':'10/14/1990'},
    {'name':'Dennis', 'age':'25', 'birthdate':'11/29/1993'},
    {'name':'Tim', 'age':'27', 'birthdate':'3/12/1991'},
    {'name':'Erik', 'age':'24', 'birthdate':'10/31/1995'},
]

  const body = document.body;
  tbl = document.createElement('TABLE');
  tbl.style.width = '100px';
  tbl.style.position = 'absolute';
  tbl.style.border = '1px solid black';
  tbl.style.marginLeft = "800px";
  tbl.style.marginTop  = "50px";

  for (var i = 0; i < myArray.length; i++){
    var row = `<tr>
            <td>${myArray[i].name}</td>
            <td>${myArray[i].age}</td>
            <td>${myArray[i].birthdate}</td>
          </tr>`
          tbl.innerHTML += row


  }

  body.appendChild(tbl);

}

Passing the return value of a useAppSelector to a variable in React-Redux

I might have missed something super obvious when refactoring my implementation of Redux in a React application, but when I’m trying to access the value of one of my slices I get thrown some errors by the Typescript Compiler about not being able to assign a (func) => string to a parameter of type string.

For context, here’s my implementation:

Slice:

export const environmentSlice = createSlice({
    name: 'environment',
    initialState,
    reducers: {
        updateEnvironment: (state, action:PayloadAction<string>) => {
            state.value = action.payload
        }
    }
});

export const { updateEnvironment } = environmentSlice.actions;

export const selectEnvironment = (state: RootState) => state.environment.value;

How i’ve defined the interface for my environment:

// Defining type for state
interface EnvironmentState {
    value: string,
};

// define the initial state using that type
const initialState: EnvironmentState = {
    value: 'live',
}

How RootState is defined in my store:


export const store = configureStore({
    reducer: {
        loggedIn: loggedInReducer,
        environment: environmentReducer,
        token: tokenReducer,
},
})

export type RootState = ReturnType<typeof store.getState>;

How I’m trying to get the value into one of my React Components:

const environment = (state: RootState) => state.environment.value;

I’ve also tried following the implementation in the redux docs here but had no luck with that: https://react-redux.js.org/tutorials/typescript-quick-start#use-typed-hooks-in-components

Zipcodes [DE]; get range of numbers in between (JavaScript) [closed]

I’ve got a string of zipcodes (which I can define myself) which I need as an array. I can do this the easy way by using the following input;

20,21,22,27,28,29,30,31,36,37,38,63,64,65,66,67,68,69,70,71,74,75,76,97,98,99

But what I would like to do is the following;

20,21,22-27,28-31,36-38,63-71,74-76,97-99

When using the input from the first example, I can create an array like this;

region_1_zipcodes.split(',');

But how is it possible to create an array with the same output, but using the second example.

I am free the use the input as I want; the example I provided isn’t leading. So if it’s better to change it into something else, it’s possible. The only requirement is that I’m using an inputfield (text) for adding the needed data.

The output should be like this;

['20', '21', '22', '27', '28', '29', '30', '31', '36', '37', '38', '63', '64', '65', '66', '67', '68', '69', '70', '71', '74', '75', '76', '97', '98', '99']

Removing elements that appear in one array from another array

I have an array of available items:

const items = [{id: 1, title: Item 1}, {id: 2, title: Item 2}, {id: 3, title: Item 3}]

and an array of items that my user has purchased:

const purchasedItems = [{id: 1, title: Item 1}, {id: 2, title: Item 2}]

I want to display an array of items that are still available to them to purchase that they haven’t bought yet, i.e. just item 3 in this case. So I want an array returned with just Item 3 in it.

I have tried:

const availableItems = items.filter(
    (item) => !purchasedItems.includes(item)
  )

However this just returns a list of all the items again.

Think I must be missing something quite obvious, any help appreciated!

What is the best approach for converting between multi-level HTML lists with arbitrary depth and JSON?

I am looking for a way to convert between arbitrarily nested HTML lists and JSON. I have started with the MDN web component example expanding-list-web-component

Example nested list –

<ul is="expanding-list" id="expl">
    <li>UK
        <ul>
            <li>Yorkshire
                <ul>
                    <li>Leeds
                        <ul>
                            <li>Train station</li>
                            <li>Town hall</li>
                            <li>Headrow</li>
                        </ul>
                    </li>
                    <li>Bradford</li>
                    <li>Hull</li>
                </ul>
            </li>
        </ul>
    </li>
    <li>USA
        <ul>
            <li>California
                <ul>
                    <li>Los Angeles</li>
                    <li>San Francisco</li>
                    <li>Berkeley</li>
                </ul>
            </li>
            <li>Nevada</li>
            <li>Oregon</li>
        </ul>
    </li>
</ul>

which could be expressed in the following JSON format-

{
  "UK": {
    "Yorkshire": {
      "Leeds": {
        "Train station": {},
        "Town hall": {},
        "Headrow": {}
      },
      "Bradford": {},
      "Hull": {}
    }
  },
  "USA": {
    "California": {
      "Los Angeles": {},
      "San Francisco": {},
      "Berkeley": {}
    },
    "Nevada": {},
    "Oregon": {}
  }
}

to extract the texts from the nested list, I tried –

const toJSON = async (elem) => {
  for (let i = 0; i < elem.childNodes.length; i += 1) {
    console.log('parentElement', elem.childNodes[i].parentElement);
    console.log('nodeType', elem.childNodes[i].nodeType);

    if (elem.childNodes[i].nodeType === 3) {
      // Node.TEXT_NODE (3) The actual Text inside an Element or Attr
      console.log('textContent', elem.childNodes[i].textContent);
    }
    toJSON(elem.childNodes[i]);
  }
};
toJSON(document.getElementById('expl'));

but this logs many newlines besides the text content and the parent child relationship is not obvious. I suspect my requirement is not uncommon and I am probably re-inventing the wheel. Is there a better approach to solving the problem?

Implementing tree sorting without creating extra function

I have a function which sorts my data tree according to it’s items order

  const itemSorter = (items) =>
  items
    .map((item) => (item?.children ? { ...item, children: itemSorter(item.children) } : item))
    .sort((i1, i2) => i1.order - i2.order);

 sortItems(dataTree);

So my question is:
Is it possible to implement the same logic without creating function itemSorter, just start with

retun dataTree.map(.... and so on) 

or that’s impossible when we use recursion and we always need the name?

JS Script using DOM running on pm2 server

I have read that serverside, you cant use DOM. I’ve created a web application using DOM and I wonder what needs to be done to reproduce this code to make it work on a server, so the people on the internet can work with it. Here is a little peak of a code:

// Listen for export button click
document.getElementById('exportForm').addEventListener('submit', function (e) {
    setTimeout(exportData, 20);
    e.preventDefault();
});

// Export data function
function exportData(e) {
    console.log("Exporting...");

    // device details and time range details
    const devId = (document.getElementById('deviceInput')).value;
    var dateFrom = (document.getElementById('dateFromInput')).value;
    var dateTo = (document.getElementById('dateToInput')).value;
    var timeFrom = (document.getElementById('timeFromInput')).value;
    var timeTo = (document.getElementById('timeToInput')).value;
    const limit = (document.getElementById('limitInput')).value;
    const key = (document.getElementById('keysInput')).value;

When I try to run it on server using pm2 start app.js, it returns this error:

ReferenceError: document is not defined
    at Object.<anonymous> (/home/cloud/sites/App/app.js:6:1)
    at Module._compile (internal/modules/cjs/loader.js:999:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14)
    at Object.<anonymous> (/usr/lib/node_modules/pm2/lib/ProcessContainerFork.js:33:23)
    at Module._compile (internal/modules/cjs/loader.js:999:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
    at Module.load (internal/modules/cjs/loader.js:863:32)
    at Function.Module._load (internal/modules/cjs/loader.js:708:14)

I’ve heard about JSDom, but I think there needs to be html included in a string and then I have no idea how to connect the css in there and so on. Is there a better way for me to make this work?

what could be the reason for this?

$ npm i body-paser
npm ERR! code E404
npm ERR! 404 Not Found – GET https://registry.npmjs.org/body-paser – Not found
npm ERR! 404
npm ERR! 404 ‘body-paser@*’ is not in this registry.
npm ERR! 404 You should bug the author to publish it (or use the name yourself!)
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.

npm ERR! A complete log of this run can be found in:
npm ERR! C:UsersuserAppDataLocalnpm-cache_logs2022-03-28T07_47_29_327Z-debug-0.log

Typescript paths results in Error: Cannot find module ‘@/common/logger’

By npm run I get Error: Cannot find module ‘@/common/logger’

VSC can recognise the paths and by typing in code it resolves correct

tsconfig.json

{
  "compilerOptions": {
    "target": "es2017",                                
    "module": "commonjs",                               
    "baseUrl": ".",                                 
    "paths": { "@/*": ["src/*"]},                              
    "outDir": "./build",                            
    "esModuleInterop": true,    
    "forceConsistentCasingInFileNames": true,            
    "strict": true,                            
    "skipLibCheck": true                              
  },
  "include": [
    "src/**/*"
  ],
  "exclude": [
    "node_modules"
  ]
}

here error by npm run

Require stack:
- /Users/vikkes/hansetag/backend/user-admin/src/iam/orgs/orgs.service.ts
- /Users/vikkes/hansetag/backend/user-admin/src/iam/users/users.service.ts
- /Users/vikkes/hansetag/backend/user-admin/src/iam/users/users.router.ts
- /Users/vikkes/hansetag/backend/user-admin/src/server.ts
- /Users/vikkes/hansetag/backend/user-admin/src/index.ts
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:999:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (/Users/vikkes/hansetag/backend/user-admin/src/iam/orgs/orgs.service.ts:13:1)
    at Module._compile (node:internal/modules/cjs/loader:1095:14)
    at Module._compile (/Users/vikkes/hansetag/backend/user-admin/node_modules/source-map-support/source-map-support.js:568:25)
    at Module.m._compile (/private/var/folders/zg/h0dstg4n2gn4cr908hw7jcdh0000gn/T/ts-node-dev-hook-20917609479276456.js:69:33)
    at Module._extensions..js (node:internal/modules/cjs/loader:1147:10)
    at require.extensions.<computed> (/private/var/folders/zg/h0dstg4n2gn4cr908hw7jcdh0000gn/T/ts-node-dev-hook-20917609479276456.js:71:20)
[ERROR] 09:45:16 Error: Cannot find module '@/common/logger'
Require stack:
- /Users/vikkes/hansetag/backend/user-admin/src/iam/orgs/orgs.service.ts
- /Users/vikkes/hansetag/backend/user-admin/src/iam/users/users.service.ts
- /Users/vikkes/hansetag/backend/user-admin/src/iam/users/users.router.ts
- /Users/vikkes/hansetag/backend/user-admin/src/server.ts
- /Users/vikkes/hansetag/backend/user-admin/src/index.ts

tsc –traceResolution shows that it resolves correct but still not able to start npm

======== Resolving module '@/common/logger' from '/Users/vikkes/hansetag/backend/user-admin/src/iam/orgs/orgs.service.ts'. ========
Module resolution kind is not specified, using 'NodeJs'.
'baseUrl' option is set to '/Users/vikkes/hansetag/backend/user-admin', using this value to resolve non-relative module name '@/common/logger'.
'paths' option is specified, looking for a pattern to match module name '@/common/logger'.
Module name '@/common/logger', matched pattern '@/*'.
Trying substitution 'src/*', candidate module location: 'src/common/logger'.
Loading module as file / folder, candidate module location '/Users/vikkes/hansetag/backend/user-admin/src/common/logger', target file type 'TypeScript'.
File '/Users/vikkes/hansetag/backend/user-admin/src/common/logger.ts' exist - use it as a name resolution result.
======== Module name '@/common/logger' was successfully resolved to '/Users/vikkes/hansetag/backend/user-admin/src/common/logger.ts'. ========