2

I have A json Object that contain some keys/values one of the values is an array I want combining the value of array from all recorded that have same key this is my Json Object

data= 
[
 {"key":11,"numbers":[555,556,557]},
 {"key":22,"numbers":[444,772,995,667]},
 {"key":11,"numbers":[223,447]},
 {"key":45,"numbers":[999,558,367]}
]

I want to get the result be like this

data= 
[
   {"key":11,"numbers":[555,556,557,223,447]},
   {"key":22,"numbers":[444,772,995,667]},
   {"key":45,"numbers":[999,558,367]}
]

I tried but I don't know how to cache the value of current matched row and try to find another matched value this is my code

data= 
[
 {"key":11,"numbers":[555,556,557]},
 {"key":22,"numbers":[444,772,995,667]},
 {"key":11,"numbers":[223,447]},
 {"key":45,"numbers":[999,558,367]}
];
function findDuplicates(data) {

 let result = [];

data.forEach(function(element, index) {

if (data.indexOf(element, index + 1) > -1) { 
  if (result.indexOf(element) === -1) {

    result.push(element.numbers.concat(data.indexOf(element, index + 1));
  }
}
});

return result;
}

console.log( findDuplicates(data) ); 

1 Answer 1

8

You can use reduce to group the array into an object. Use concat to merge arrays. Use Object.values to convert the object to array.

let data = [
  {"key":11,"numbers":[555,556,557]},
  {"key":22,"numbers":[444,772,995,667]},
  {"key":11,"numbers":[223,447]},
  {"key":45,"numbers":[999,558,367]},
  {"key":45,"numbers":100}
];

let result = Object.values(data.reduce((c, {key,numbers}) => {
  c[key] = c[key] || {key,numbers: []};
  c[key].numbers = c[key].numbers.concat(Array.isArray(numbers) ? numbers : [numbers]); 
  return c;
}, {}));

console.log(result);

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

3 Comments

good that's working but what if the number value is single instead of array i mean be a single value like '"numbers":345'
@Eddie consider using Array.isArray rather than isNaN, as it is more honest about what is being tested for
@PaulS. Thanks for the suggestion :)

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.