Home > OS >  convert comma separated array of element to integer value in javascript
convert comma separated array of element to integer value in javascript

Time:05-05

i have got one array with string value which contain comma separator.

const array = [
  "65,755.47",
  0,
  null,
  0,
]

i want to remove the string from the value and other value remain constant in the array.

so the the output should be:--

const array = [
  65,755.47,
  0,
  null,
  0,
]

How can i achieve this?Thanks!!

CodePudding user response:

You can do it with a flat map

const arr = ["65,755.47", 0, null, 0];

const res = arr.flatMap((el) => {
  if (typeof el === "string") {
    return el.split(",").map((n) =>  n);
  }
  return el;
});

console.log(res);

CodePudding user response:

you can do this

const data = [
  "65,755.47",
  0,
  null,
  0,
]


const result1 = data.map(v => typeof v === 'string'?v.split(',').map(Number): v)
const result2 = data.flatMap(v => typeof v === 'string'?v.split(',').map(Number): v)

console.log(result1)
console.log(result2)

CodePudding user response:

function doSomething() {
  const input = ["65, 755.47", 0, null, 0];
  input[0] = input[0].split(",").map((num) => parseFloat(num));
  return input.flat()
}
console.log(doSomething())

This should work if your input array does not change over time.

CodePudding user response:

Given the array

const array = ["65755.47", 0, null, 0];

You can run this

const converted = array.map((item) => item ? Number(item) : item)

Or alternatively, you have strings with comma

const array2 = ["65,755.47", 0, null, 0];

you should remove commas before converting the item

const converted2 = array2.map((item) =>
  typeof item === "string" ? parseFloat(item.replace(/,/g, "")) : item
);

CodePudding user response:

function doSomething() {
    let x = [];
    const input = ["65, 755.47, 45", 0, null, 0];
    input.forEach(element => {
        // check is string
        if (typeof element === 'string' || element instanceof String) {
            x = x.concat(element.split(',').map((e)=>parseFloat(e)));
        } else {
            x.push(element);
        }
    })
    return x;
  }
console.log(doSomething())

it' oke

  • Related