Home > Mobile >  Split multiple value in Array & create new array for split value in Java script
Split multiple value in Array & create new array for split value in Java script

Time:07-23

I want all index value that have data in array after ":" & split it to different Array at same index number. I am able to change data for one index value but its not changing for all value

var Array = ["Alice:", "John:654", "Bob:123"];

** After Split **
var Array = ["Alice:", "John:", "Bob:"];
var new array = ["", "654", "123"];

<script>
var array = ["Alice:", "John:654", "Bob:123"];

var el = array.find(a =>a.includes(":"));
let index = array.indexOf(el);
const newArray = el.split(':')[0]   ':';

var array2 = ["", "", ""];
array2[index] = newArray;

document.getElementById("demo").innerHTML = "The value of arry is: "   el;
document.getElementById("demo2").innerHTML = "The index of arry is: "   index;
document.getElementById("demo3").innerHTML = "split value: "   newArray;
document.getElementById("demo4").innerHTML = "new arr: "   array2;
</script>

CodePudding user response:

If I understood your question correctly, this should be a solution:

const [oldOne, newOne] = array.reduce(
    (acumm, current, index) => {
        const [name, value] = current.split(':');
        acumm[0].push(`${name}:`);
        acumm[1].push(value ?? '');
       return acumm;
     },
     [[], []]
);

Stackblitz Example

Info

// not mess up global vars, "Array" is a constructor
var Array = ["Alice:", "John:654", "Bob:123"];

** After Split **
var Array = ["Alice:", "John:", "Bob:"];

// not mess up with key words, "new" can only be called on 
// constructors and array is as far i know not one
var new array = ["", "654", "123"];

CodePudding user response:

Here's a solution using .map (so you don't need to keep track of the index)

var array = ["Alice:", "John:654", "Bob:123"];

var result = array.map(e => e.split(":")[1])
array = array.map(e => e.split(":")[0]   ":")

console.log(array, result)

Note that split(":")[1] will only give you the first entry if you have multiple ":" in the values, eg "John:654:999" - you can combine them with splice and join, eg:

parts.splice(1).join(":")

Here's the same solution, using a forEach if you prefer a single iteration over two:

var array = ["Alice:", "John:654:999", "Bob:123"];

var result = [];
var replacement = [];

array.forEach(e => {
  var parts = e.split(":");
  replacement.push(parts[0]   ":")
  result.push(parts.splice(1).join(":"))
});

console.log(replacement, result)

  • Related