0

I have few arrays of JSON objects.I need to iterate over the arrays and return true if there are two or more elements with the same userId value.

[{
"name":"John",
"age":30,
"userId": 5,
}],

[{
"name":"Benjamin",
"age":17,
"userId": 5,
}],

[{
"name":"Johnatan",
"age":35,
"userId": 10,
}]

Here is my method so far, I'm iterating over the array and checking is there a user with 506 userId presence.

isPostedMultiple = (data) => {
 for (let j = 0; j < data.length; j++) {
   if (data[j].UserId == '506') {
    console.log('506 data :', data[j]);
   } else {
    console.log('not 506 data'); 
   }
 }
}
3
  • 2
    And what did not work? Commented Mar 15, 2018 at 20:54
  • Invalid syntax, please make it possible to compile Commented Mar 15, 2018 at 20:56
  • I don't know how to compare two element values from arrays Commented Mar 15, 2018 at 20:58

5 Answers 5

3

First of all the Object you have given is erroneous. Make it correct. Coming to the problem, You can use a combination of Array.prototype.some and Array.prototype.filter.

data.some(
  (el, i, arr) => arr.filter(_el => _el.userId == el.userId).length > 1
);

To check if there exists more than one element matching certain condition.

var data = [{
    "name": "John",
    "age": 30,
    "userId": 5,
  },
  {
    "name": "Benjamin",
    "age": 17,
    "userId": 5,
  },
  {
    "name": "Johnatan",
    "age": 35,
    "userId": 10,
  }
];

var result = data.some(
  (el, i, arr) => arr.filter(_el => _el.userId == el.userId).length > 1
);

console.log(result)

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

4 Comments

Not my downvote, but you don't explain how your answer works and it seems inefficient to iterate over the array a maximum of length^2 times.
It will work but only for one arr, in example there are 3 arrays
Why not just use a nested some? No need create another array using filter and it will stop iterating when the first true is returned.
Agreed, this json makes more sense.
1

You can merge arrays using array spread syntax and than use the reduce with the filter method

const mergedArrays = [...arr1, ...arr2, ...arr3];
const isDublicated = mergedArrays.reduce(
  (acc, item) => acc || mergedArrays.filter(user => user.userId === item.userId) > 1,
  false
);

5 Comments

Why not just use [...arr1, ...arr2, ...arr3].filter((item, index, source) => source.some(u => u.userId === item.userId))? Not sure what value reduce is adding?
Note that this solution is for ES6 or greater and will not work in older browsers.
@sellmeadog couse I didn't think about that solution, but you are right it's clearer.
This hard codes the number of source arrays (in this case, 3), creates an unnecessary additional array and loops over the resulting array up to length times (in this case, 3) so is inefficient.
0

To achieve expected result, use below option of using filter and findIndex to iterate over every array and compare userId

var x = [[{
"name":"John",
"age":30,
"userId": 5,
}],

[{
"name":"Benjamin",
"age":17,
"userId": 5,
}],

[{
"name":"Johnatan",
"age":35,
"userId": 10,
}]]

x = x.filter((v, i, self) =>
  i === self.findIndex((y) => (
     y[0].userId === v[0].userId
  ))
)


console.log(x);

code sample - https://codepen.io/nagasai/pen/wmWqdY?editors=1011

Comments

0

var jsonObj1 = [{
"name":"John",
"age":30,
"userId": 5
},

{
"name":"Benjamin",
"age":17,
"userId": 5
},

{
"name":"Johnatan",
"age":35,
"userId": 10
}];

var jsonObj2 = [{
"name":"John",
"age":30,
"userId": 5
},

{
"name":"Benjamin",
"age":17,
"userId": 15
},

{
"name":"Johnatan",
"age":35,
"userId": 10
}];

var logger = document.getElementById('logger');
logger.innerHTML = "";

function checkForDupIds(jsonObj, headerStr) {
  var logger = document.getElementById('logger');
  var hasDups = [];
  var items = [];
  for(var a=0;a<jsonObj.length;a++) {
    if (items.includes(jsonObj[a].userId)) {
      hasDups.push(jsonObj[a].userId);
    } else {
      items.push(jsonObj[a].userId);
    }
  }
  logger.innerHTML += "<h1>" + headerStr + "</h1>";
  for(var b=0;b<hasDups.length;b++) {
    logger.innerHTML += "<div>" + hasDups[b] + "</div>\n";
    console.log(hasDups[b]);
  }
  if (hasDups.length === 0) {
    logger.innerHTML += "<div>No Duplicates Found</div>\n";
  }
}

checkForDupIds(jsonObj1, "jsonObj1");
checkForDupIds(jsonObj2, "jsonObj2");
<html>
<body>
<div id='logger'></div>
</body>
</html>

Comments

0

You can loop over the array and keep a count of how many times each userId value appears. If you get to 2 for any value, stop and return false (or some other suitable value).

Array.prototype.some allows looping over the array until the condition is true, so it only loops over the source once. The data in the OP was invalid, I've modified it to be an array of objects.

var data = [{
"name":"John",
"age":30,
"userId": 5
},
{
"name":"Benjamin",
"age":17,
"userId": 5
},
{
"name":"Johnatan",
"age":35,
"userId": 10
}]

function hasDupIDs(data) {
  // Store for userId values
  var ids = {};
  // Loop over values until condition returns true
  return data.some(function(x) {
    // If haven't seen this id before, add to ids
    if (!ids.hasOwnProperty(x.userId)) ids[x.userId] = 0;
    // Increment count
    ids[x.userId]++;
    // Return true if second instance
    return ids[x.userId] > 1;
  });
}

console.log(hasDupIDs(data));

If you want more concise code, you can use:

var data = [
  {"name":"John","age":30,"userId": 5},
  {"name":"Benjamin","age":17,"userId": 5},
  {"name":"Johnatan","age":35,"userId": 10}];

function hasDupIDs(data) {
  var ids = {};
  return data.some(x => {
    ids[x.userId] || (ids[x.userId] = 0);
    return ++ids[x.userId] > 1;
  });
}

console.log(hasDupIDs(data));

3 Comments

I think your assumption that the data in the original question is invalid is incorrect. I think the OP was clearly asking given N disparate arrays, how do I find duplicates between them which your answer does not do. However, your solution would obviously work after the source arrays have been concatenated.
@sellmeadog—the OP's code contains syntax errors, so how is the statement "The data in the OP was invalid" incorrect? Another answer says the same thing. I guessed at a way to turn it into valid code, as have others. I posted this answer as I think it's much more efficient than others, particularly the accepted answer.
I am not arguing the OP's syntax errors, but that aside, I still believe the sample data was provided to indicate that the goal is to find duplicates across disparate, same-shaped arrays. It's entirely possible I'm wrong.

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.