-1

I have an array as below

var abc = [11,2,11,3,11,4,9,5]

I am actually appending the data into datatables, and it would be like this as of now

11|2
11|3
11|4
9 |5

So my question is, i want it to check if there is a duplicate/same value in index 0, and add everything in index 1, example as below

11|9
9 |5

Is is possible for me to do that? I have tried the below but still not working

for (var a = 0; a < x.length; a++) {    
  if (x[0] !== -1){
     alert(x[0]);
    } else {
     console.log("no same value found");
    }
}

But still no luck making it to work. Appreciate any help that i can get.

Thanks

justarandomguy
  • 145
  • 1
  • 13
  • `if (x[0] !== -1){` does not seem anything like trying to see if a value is unique. The syntax of your input is not valid either – CertainPerformance Jan 21 '20 at 07:46
  • Did you look at what your `abc` array actually contains? Try the following in the JavaScript console and look at what it displays. Is it what you expect? `console.log([11,2|11,3|11,4|9,5])` – Michael Geary Jan 21 '20 at 07:49
  • Im sorry to the commenters,but none of the links that you provide solve my question, and i dont understand why im getting my topic closed as it does not solve my question – justarandomguy Jan 21 '20 at 08:02

1 Answers1

1

You could iterate the array by step of two and get key and value for looking for the same group.

If not found add a new group to the result set.

At last add the value to the group.

var data = [11, 2, 11, 3, 11, 4, 9, 5],
    result = [];

for (let i = 0; i < data.length; i += 2) {
    let key = data[i],
        value = data[i + 1],
        group = result.find(([q]) => q === key);

    if (!group) result.push(group = [key, 0]);
    group[1] += value;
}

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392