简体   繁体   中英

convert comma separated array of element to integer value in javascript

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!!

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);

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)

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
);

 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM