1

I have an array with values

myarray=["Mark:40", "John:20", "Sofia: 60", "Mark:30"]

desiredArray=["Mark:70", "John:20", "Sofia: 60"]

It should check whether the names are unique and if it found same name multiple times, it should add the marks and make the desired array with distinct elements. I am able to get unique array but not able to merge the marks. Could anyone help?

Eddie
  • 26,593
  • 6
  • 36
  • 58
Harry
  • 33
  • 5

5 Answers5

1

You could take a Map for collecting the values and render new strings for the result.

var array = ["Mark:40", "John:20", "Sofia: 60", "Mark:30"],
    result = Array.from(
        array.reduce(
            (m, s) => (([k, v]) => m.set(k, (m.get(k) || 0) + +v))(s.split(/:\s*/)),
            new Map
        ).entries(),
        a => a.join(':')
    );

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You can group the array by using reduce. Use Object.entries to convert the object into an array and map to form the desired output.

let myarray = ["Mark:40", "John:20", "Sofia: 60", "Mark:30"];

let desiredArray = Object.entries(myarray.reduce((c, v) => {
  let [n, a] = v.split(':');
  c[n] = c[n] || 0;
  c[n] += +a;
  return c;
}, {})).map(o => o[0] + ":" + o[1]);

console.log(desiredArray);
Eddie
  • 26,593
  • 6
  • 36
  • 58
0

You can choose to go with simple for loop also:

var myarray=["Mark:40", "John:20", "Sofia: 60", "Mark:30"];
for(var i=0; i<myarray.length; i++){
  var splitVal = myarray[i].split(":");
  var nameI = splitVal[0];
  var scoreI = parseInt(splitVal[1]);
  for(var j=i+1; j<myarray.length; j++){
    splitVal = myarray[j].split(":");
    var nameJ = splitVal[0];
    if(nameI === nameJ){
      scoreI += parseInt(splitVal[1]);
      myarray.splice(j,1);
    }
  }
   myarray[i] = nameI+":"+scoreI;
}
console.log(myarray);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
0

A simple approach would be to iterate over the new array every time that you would like to add a new value and check whether or not the key exists. If it does increment the value, if not add it.

Here is one solution with a temporary object.

// Initial array
const myarray = ["Mark:40", "John:20", "Sofia: 60", "Mark:30"]
// Temporary object used to calculate values
const desired = {};

for (let value of myarray) {
  // Index of the first digit in the string
  const separatorIndex = value.indexOf(':') + 1;
  // Key is everything before the first digit including the :
  let key = value.substr(0, separatorIndex);
  // If the key isn't present in the object add it
  if (desired[key] === undefined) {
    desired[key] = 0;
  }
  // Add the value of the key to the temporary object
  // this combines the values of equal keys
  desired[key] += parseFloat(value.substr(separatorIndex));
}

const desiredArray = [];
// Create an array from all values
for (let key in desired) {
  desiredArray.push(key + desired[key].toString());
}

console.log(desiredArray);
Ognyan M
  • 104
  • 1
  • 8
0

You can do:

const array = ["Mark:40", "John:20", "Sofia: 60", "Mark:30"];
const temp = array.reduce((a, c, i, arr) => {
  const u = c.split(':');
  a[u[0]] = a[u[0]] + +u[1] || +u[1];
  return a;
}, {});
const result = Object.keys(temp)
  .map(u => `${u}:${temp[u]}`);

console.log(result);
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46