Home > Software engineering >  How can i separate number and string from an Array collection in JavaScript?
How can i separate number and string from an Array collection in JavaScript?

Time:01-05

I am learning JavaScript, I want to separate number and string from an Array collection. I can't do this. Can anyone help me how can i do this?

Here is my code example:

const array = [1, 'abc', 3, 'def', 5, 'ghi'];

I want like this:

[1, 3, 5]
['abc', 'def', 'ghi']

How can i do this?

CodePudding user response:

You can do this with JavaScript built-in array.filter() method.

Here is the solution:

const array = [1, 'abc', 3, 'def', 5, 'ghi'];

const numbers = array.filter((item) => typeof item === "number");
const strings = array.filter((item) => typeof item === "string");

console.log(numbers); // [1, 3, 5]
console.log(strings); // ['abc', 'def', 'ghi']

I think it will solve your problem.

CodePudding user response:

You could create a function that separates them like so:

function seperate(arr) {
  var numbers = [];
  var strings = [];
  for (var i in arr) {
    if (isNaN(arr[i])) {
      strings.push(arr[i]);
    } else {
      numbers.push(arr[i]);
    }
  }
  return [numbers, strings];
}

This works by cycling through each value in the original array. Then it uses the isNaN() method to check if the value is a number. If it is, it puts that value in the numbers array. If it's not, it puts it in the strings array. Then it returns both arrays.

CodePudding user response:

Use reduce() to create an object were we use typeof element to determine in what category it should be placed:

const array = [1, 'abc', 3, 'def', 5, 'ghi'];

const result = array.reduce((p, c) => {
    let type = typeof c;
    return { ...p, [type]: [ ...(p[type] || []), c ] }
}, { });

console.log(result)

{
  "number": [
    1,
    3,
    5
  ],
  "string": [
    "abc",
    "def",
    "ghi"
  ]
}

CodePudding user response:

const array = [1, 'abc', 3, 'def', 5, 'ghi'];

const strings = array.filter(elem => isNaN(elem));
const numbers = array.filter(elem => !isNaN(elem));

CodePudding user response:

const mixedArray = [1, 'abc', 3, 'def', 5, 'ghi'];
const strings = [...mixedArray.filter(num => isNaN(num))]; // ['abc', 'def', 'ghi']
const numbers = [...mixedArray.filter(num => !isNaN(num))]; // [1,3,5]

CodePudding user response:

simple function to filter not only string and number but any type data.

const array = [1, 'abc', 3, 'def', 5, 'ghi', false, null, [], '4', function(){}];

function arrayTypeFilter_(){
  let res = {};
  for(let a of array){
    let key_ = typeof a; if( !res[key_] ){ res[key_] = []; }
    res[key_].push(a);
  }
  return res;
}

console.log( arrayTypeFilter_(array) );

CodePudding user response:

const array = [1, 'abc', 3, 'def', 5, 'ghi'];;

const getValuesFromArray = (arr, type) => {
    const result = [];

    arr.forEach(value => {
      if (typeof value !== type) {
        return;
      }

      result.push(value)
    }) 

   return result;
  }

const numbersArr = getValuesFromArray(array, 'number');
const strArr = getValuesFromArray(array, 'string');

CodePudding user response:

You should leverage the built-in typeof operator to check for the types of each array element and then place them in the appropriate category.

const input = [1, 'abc', 3, 'def', 5, 'ghi'];

const allNumbers = [];
const allStrings = [];

input.forEach((x) => {
  if (typeof x === 'number') {
    allNumbers.push(x);
  } else if (typeof x === 'string') {
    allStrings.push(x);
  }
});

console.log(allNumbers); // [1, 3, 5]
console.log(allStrings); // ['abc', 'def', 'ghi']

  • Related