Below is the input data:
const arr = [10,20,[40,50,60],70,80,[90,100],111,112];
The desired output is as follows:
{10:10,20:20,'array1':{40:40,50:50,60:60},70:70,80:80,'array2':{90:90,100:100},111:111,112:112}
Below is the input data:
const arr = [10,20,[40,50,60],70,80,[90,100],111,112];
The desired output is as follows:
{10:10,20:20,'array1':{40:40,50:50,60:60},70:70,80:80,'array2':{90:90,100:100},111:111,112:112}
My method involves utilizing the Array.prototype.reduce() function, but it is only capable of handling arrays with a single level of nesting.
const arr = [10,20,[40,50,60],70,80,[90,100],111,112];
let count=1;
let a = arr.reduce((acc,curr) => {
if(Array.isArray(curr)){
let b = curr.reduce((acc1,curr1)=> {
acc1[curr1] = curr1;
return acc1
},{})
acc[`array${count}`] = b;
count+=1;
}
else{
acc[curr] = curr;
}
return acc;
},{})
console.log(a)
As the output is an object, the order may not necessarily match the input array structure.
To simplify the process, iterate through the array and create a new object along the way:
let count = 1;
let newObj = {}
arr.forEach((item) => {
if(Number.isInteger(item)){
newObj[item] = item;
} else {
subObj = {}
item.forEach((subItem) => subObj[subItem] = subItem);
newObj[`array${count}`] = subObj;
count += 1;
}
})
Check out this recursive solution using reduce(), which can handle deeply nested arrays as well.
function extractArrayValues(array){
let arrayCounter = 0;
return array.reduce((result, current) => {
if (!Array.isArray(current)) result[current] = current;
else {
arrayCounter += 1;
result[`array${arrayCounter}`] = extractArrayValues(current);
}
return result;
}, {})
}
const sampleArray = [10, 20, [40, 50, 60], 70, 80, [90, 100], 111, 112];
console.log(extractArrayValues(sampleArray));
const nestedArray = [10, 20, [40, 50, 60], 70, 80, [90, 100, [40, 50, 60]], 111, 112];
console.log(extractArrayValues(nestedArray));
Currently utilizing the WowBook plugin and looking to intercept the click event on the page turning link. Specifically, I am aiming to redirect the user to a different URL when they reach the end of the "pages" (div containers). Despite my efforts in the ...
I am attempting to create a specific scenario where I can restrict my string to three digits, followed by a dot and two optional digits after the dot. For example: 100.00 1 10.56 31.5 I've developed a regex pattern that allows me to filter out any ...
Why do functions produce different results when the parameter order is changed? For instance: Code Sample #include <stdio.h> #define MAX_SIZE 100 void sum2(float *list, int n); void sum3(int n, float *list); float input[MAX_SIZE]; int main(void){ ...
Within my project, I have set up a canvas where I am able to: Load an image onto the canvas Resize the uploaded image Currently, I am working on implementing a rotate function that allows me to rotate the loaded image within the canvas by holding down th ...
For a school assignment, I am working on finding the longest line in a piece of code. I have encountered a puzzling situation where the "longest_line" variable prints correctly within the while loop but not outside of it. int main() { int ch; char ...
Code to retrieve data from a database: public function getOneByName($name){ try{ $link = DB_Helper::createMySQLConnection(); $query = "Select * From vendor Where vendor_name=?"; $stmt = $link->prepare($query); $stmt->bindVal ...
I am facing an issue while trying to apply some design on the next element. The error message that I am encountering is: Error: Syntax error, unrecognized expression: [object Object] > label Below are my selections for browsing by category: BROWSE BY ...
I've been struggling to get this basic piece of code to work properly, despite trying numerous resources. I can't seem to pinpoint where I'm going wrong. Essentially, I have a javascript function submitData() that is supposed to make an ajax ...
When working in JavaScript, I typically define an array like this: var arr = [1,2,3]; It's also possible to do something like: arr[-1] = 4; However, if I were to then set arr to undefined using: arr = undefined; I lose reference to the value at ...
I've been grappling with this issue for the majority of today; I'm trying to tally up the number of childNodes within a parent div. It's essentially mimicking a list where each childNode represents a row that I want to count. The HTML struct ...
I am looking to 'modify' a file that is stored on my server, for example: <link rel="stylesheet" href="css/plugin.scss"> Not only that, but I also want to specifically edit a line within the SASS file. In SASS, you can declare variables i ...
My HTML code snippet is structured as follows: <custom-logo> <div> <img src="logo.png"> </div> <custom-logo-after> </custom-logo-after> </custom-logo> I'm working on modifying the cus ...
Just diving into the world of angularJs, I find myself faced with the challenge of upgrading an app from version 0.9 to 1.0.5. The function '$add' called on an array has me stumped. Despite hours of searching through documentation, I still can&ap ...
Looking into a similar question that was posted on StackOverflow - How to check if a value exists in an array in Android In my FragmentActivity, I have 3 arrays set up as follows: String[] productName = {"Bread", "Butter", "Cadburry", "Tin Spinach", ...
Within my application, I have a list that necessitates the use of an "or" condition. However, according to the documentation: "In this case, you should create a separate query for each OR condition and merge the query results in your app." Consequently ...
I am a newcomer to utilizing phantomjs and encountering difficulties in rendering my website as a PDF file. Although I can successfully render a simple version of the page, issues arise when multiple images and web fonts are involved, causing the DOM not t ...
In my React components, I am initializing state like this: export default class LoginForm extends Component { state = { // (*) flash: { message: null, style: null } // initialiser for flash message: show no ...
Encountering an issue while attempting to pass variables to a PostgreSQL database: Error: syntax error at or near "," const rb = req.body; const sql= "insert into test1 (user, name, created) values (?, ?, CURRENT_TIMESTAMP);" poo ...
I am in the process of incorporating a CSS module into the login component. Currently, I have a style.css stylesheet located in the src/styles folder, which is responsible for loading global styles. However, I now want to customize the login component by a ...
After clicking a button, I want to load a div and not have it load on page load. I specifically mentioned loading the div after clicking the button, not just showing it. The code is working, but I need help implementing it in WordPress. <div id="cont ...