0

I have array of arrays called user_list that looks something like this:

[[user3, 12], [user2, 10], [user1, 5], [user5, 5], [user4, 4]]

First column contains usernames and second their balance. I've already sorted them by balance, and now I have to remove all rows that have same balance and add users that have different balance to new array called unique_user_list.

So, expected result is:

[[user3, 12], [user2, 10], [user4, 4]]

Here's my loop (that doesn't work).

for(var i = 0; i<user_list.length; i++) {
    var unique = user_list[i][1];
    for(var j = 1; j<user_list.length; j++) {
        if(unique!=user_list[j][1]) {
            unique_user_list[i] = user_list[i][0];
        }
    }
}
3
  • Would you be fine with splicing the elements from the original array? I fell that doing this would make it simpler. Commented Feb 14, 2016 at 16:09
  • @KevinWang: Could you please be more specific or show me example? I'm totally new to JavaScript. Commented Feb 14, 2016 at 16:22
  • There is a way that you can remove the elements from the array, and with this method you can just remove all elements from the user_list that have duplicate balances. Commented Feb 14, 2016 at 16:27

2 Answers 2

1

There's probably a better way to do this, but you can make it work like this:

function getUnique() {
  var unique_user_list = [];
  for (var i = 0; i < user_list.length; i++) {
    var unique = user_list[i][1];
    var match = false;
    for (var j = 0; j < user_list.length; j++) {
      if (unique == user_list[j][1] && j != i) {
        match = true;
      }
    }
    if (!match) {
      unique_user_list.push(user_list[i]);
    }
  }
  return unique_user_list;
}

You want to make sure j != i, so you're not checking the value equals itself. And you want to push to your output array in the outer loop for the same reason.

https://jsfiddle.net/sco_tt/w704p6kt/

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

Comments

0

This solution features Array#filter() for the filtering of the balances with a single loop only.

var data = [['user3', 12], ['user2', 10], ['user1', 5], ['user5', 5], ['user4', 4]],
    lastBalance,
    filtered = data.filter(function (a, i, aa) {
        if (i + 1 < aa.length && a[1] === aa[i + 1][1]) {
            lastBalance = a[1];
            return false;
        }
        return a[1] !== lastBalance;
    });

document.write('<pre>' + JSON.stringify(filtered, 0, 4) + '</pre>');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.