Home > front end >  If array contains different type elements, how to pick the same type elements and create new array w
If array contains different type elements, how to pick the same type elements and create new array w

Time:10-14

Hi! So I want to get the following result: enter image description here

and here's the js function that i wrote. The problem is that the output of my function is null.

function dataTypeArray(arr, type){
    for(i=0; i<=arr.length-1; i  )
    var string = [];
    var number = [];
    var boolean = [];
    var i;
    if(type = 'string' && typeof arr[i] == 'string'){
        string.push(arr[i]);
    } else {
        if(type = 'number' && typeof arr[i] == 'number'){
            number.push(arr[i]);
        } else {
            if(type = 'boolean' && typeof arr[i] == 'boolean'){
                boolean.push(arr[i]);
            } else { 
                return 'null';
            }}} 
        return string, number, boolean;}


var arr = ['hhg', 'fthth', 456, true];
console.log(dataTypeArray(arr, 'string'));

CodePudding user response:

I'd suggest using Array.prototype.filter.

var arr = ['hhg', 'fthth', 456, true];
var strings = arr.filter(x => typeof x === 'string');
var numbers = arr.filter(x => typeof x === 'number');
var booleans = arr.filter(x => typeof x === 'boolean');

CodePudding user response:

Rajesh has already listed in their comment what is going wrong in your current code. I'd recommend you to move to modern JavaScript, the task becomes quite easy:

function getTypeMap(arr) {
  const typeMap = {};
  for (const val of arr) {
    const key = typeof val;
    typeMap[key]?.push(val) ?? (typeMap[key] = [val]);
  }
  return typeMap;
}

const exampleArr = [0, 'a', 1, 'b', true, 2, false],
  {boolean, number, string} = getTypeMap(exampleArr);

console.log(boolean, number, string);

As said, you can't return multiple values from a function. Here we create an object with keys by types of the values in the array, and return the object. In the loop, the code checks whether a property named by the type of the value exists using optional chaining operator, if the operator returns undefined we'll create a new array with the current value in the first index (see nullish coalescing operator), otherwise we just push a new value to the type array.

Properties from the returned object are then assigned to variables using destructuring assignment ({boolean, number, string} = ...). This way you can get any type of the values in the array mapped, just pick those you need when destructuring the returned object to the variables, or store the returned object to a variable, and use its properties where needed.

  • Related