-1

I need your help: I have an Array (data) containing objects:

var data = [
0: Object { hex: "#ff847f", length: "20" }
1: Object { hex: "#afff90", length: "18" }
2: Object { hex: "#afff90", length: "40" }
3: Object { hex: "#6d91b0", length: "30" }
4: Object { hex: "#ff847f", length: "20" }
]

I need a function, that results me an new Array, which has only unique hex-values AND add up the length-values of the equal hex-values.

The result should look like this:

var data2 = [
0: Object { hex: "#ff847f", length: "40" }
1: Object { hex: "#afff90", length: "58" }
2: Object { hex: "#6d91b0", length: "30" }
]

Thanks for ur ideas.

  • Possible duplicate of [Better way to sum a property value in an array (Using Angularjs)](https://stackoverflow.com/questions/23247859/better-way-to-sum-a-property-value-in-an-array-using-angularjs) – Mohammad Usman Apr 15 '18 at 13:05
  • At least show some effort that you attempted to write a JavaScript function before we do your homework. – zer00ne Apr 15 '18 at 16:15
  • Sorry, but i had no idea. In addition, nobody forces you to do my "homework" – zerberster123 Apr 15 '18 at 19:58

1 Answers1

0

This is probably not the best solution, but it works. The challenging bit is the fact that you want your length as a string instead of a number. Here is my solution, I hope it helps!

const transformArray = (arr) => {
  //first you need to convert the lengths to numbers to make adding easier
  arr.map((item) => {
    item.length = Number(item.length)
  })
  
  //then combine like objects
  let output = [];
  arr.forEach((dataObj) => {
    let found=false;
    for (let i=0; i<output.length; i++) {
      if (output[i].hex === dataObj.hex) {
        output[i].length+= dataObj.length;
        found=true;
      }
    }
      if (found===false) {
        output.push(dataObj)
      }
  }); 
  
  //then convert your lengths back to strings
  arr.map((item) => {
    item.length = item.length.toString();
  })
  
  return output;
}