-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

3
  • 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 Commented Jan 21, 2020 at 7: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]) Commented Jan 21, 2020 at 7: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 Commented Jan 21, 2020 at 8:02

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much, this solve my question, better than any other solutions provided. Appreciate your help

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.