Generation

generate functionFri, 09 Jun 2023

You've got a nifty little program that collects a bunch of data, but it's returning data as it comes in in the form of an array. The data coming in is in a random order. That's not so good, because you want to be able to easily read and use this information. To make the data easier to manage, use a for loop to sort out your data by its type. Return an array with all the values in it, sorted by letters first, followed by numbers, then objects. Be aware that your nifty program sometimes returns nested arrays with their own elements in them. function separateDataTypes(arr) {

function separateDataTypes(arr) { var stringArray = []; var numberArray = []; var objectArray = []; for (var i = 0; i < arr.length; i++){ if (typeof arr[i] === "string") { stringArray.push(arr[i]); } else if (typeof arr[i] === "number") { numberArray.push(arr[i]); } else if (typeof arr[i] === "object") { objectArray.push(arr[i]); } } return stringArray.concat(numberArray).concat(objectArray); } separateDataTypes([1, "a", "b", "c", 2, 3, 4, 5, null, {}, {}, {}]);

Javascript
Generate More

Questions about programming?Chat with your personal AI assistant