0

my code speed performance very slow when to get unique value from array that existing 5000 users data.

There is my code below which has two conditions:

First, to get unique value

Second, to check phone number is null or not, given preference to users data that existing phone number/s.

var arr = [
 ["Wong", ""],
 ["Wong", "0143213123"],
 ["Ali", "0177213123"],
 ["Ali", "0177213123, 0124545345"],
 ["Ali", ""],
 ["Imran", "0133454335"]
];
function uniq(arr) {
 var seen = [];
 for (i = 0; i < arr.length; i++) {
 var a = arr[i][0];
 var a2 = arr[i][1];
 var c = true;
 for (x = 0; x < seen.length; x++) {
 var b = seen[x][0];
 var b2 = seen[x][1];
 if (b == a) {
 c = false;
 if ((b2.trim() == '' || b2.indexOf(',') == -1) && (a2.trim() != '')) {
 seen[x][1] = a2.trim();
 break;
 }
 break;
 }
 }
 if (c == true) {
 seen.push(arr[i]);
 }
 }
 return seen;
}

Result, after code executed:

var arr = uniq(arr);
console.log(arr);
[
 ["Wong", "0143213123"],
 ["Ali", "0177213123, 0124545345"],
 ["Imran", "0133454335"]
];

In jsfiddle here

Niladri Basu
10.7k7 gold badges59 silver badges65 bronze badges
asked Aug 3, 2018 at 9:17

1 Answer 1

3

You could do something like this with reduce and store data in one object for each name.

var arr = [["Wong",""], ["Wong", "0143213123"], ["Ali", "0177213123"], ["Ali", "0177213123, 0124545345"], ["Ali", ""], ["Imran", "0133454335"]];
var uniq = arr.reduce((r, [name, number]) => {
 if(!r[name] || number.trim().length) r[name] = number;
 return r;
}, {});
console.log(Object.entries(uniq))

answered Aug 3, 2018 at 9:29

1 Comment

Thank @Nenad Vracar , i will test and feedback later (y)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.