Home > Software engineering >  How to get distinct values from array in JavaScript?
How to get distinct values from array in JavaScript?

Time:11-25

Assuming I have the following:

var array =

[
    {"name":"Joe", "age":null, "date":"1959-08-10", "home":"ny"}
],
[
    {"name":"Bill", "age":null, "date":"1956-08-10", "home":"tx"}
],
[
    {"name":"Joe", "age":"17", "date":null, "home":"ny"}
],
[
    {"name":null, "age":"17", "date":"1956-08-10", "home":"tx"}
],
[
    {"name":"Joe", "age":"17", "date":"1959-08-10", "home":null}
]

What is the best way to be able to get an new array:

var new_array =

[
    {"name":"Joe", "age":"17", "date":"1959-08-10", "home":"ny"}
],
[
    {"name":"Bill", "age":"17", "date":"1956-08-10", "home":"tx"}
]

CodePudding user response:

There are basically four options available to you: A regular loop, or the map, filter, reduce functions on the array instance, for example:

var oldArray = [1, 2, 3, 4, 5];
var newArray = oldArray.filter((item) => item > 2); // Gives you [3, 4, 5] 

Have a look at mdn for a more specific description. This link is to filter, but map and reduce can be found in the left sidepanel.

Edit The loop method:

var oldArray = [1, 2, 3, 4, 5];
var newArray = [];

for (var item of oldArray) {
  if (item > 2) {
    newArray.push(item);
  }
}
newArray; // Gives you [3, 4, 5]

CodePudding user response:

Bill and Joe are the reference points.
You need to loop through the array and test for name and store (in another array) non-null values.
Also, are there only two names?
You probably need to allow for a variable number of names.
this is far from complete code but will hopefully get you started.
Also look at foreach
You need to at least show what you have tried to make discussion and debug easier!

var dataCollect=[];
for (i=0; i<array.length; i  ) {    
    if (array[i]['name'] != null) { name = array[i]['name'];
    /* then your range of qualifiers gets complicated
eg. array[3] has no name so how to know what this relates to?
you probably need another internal loop to test !=null
to get values for x y z */
    dataCollect.push ({
name: name,
age: 'x',
date: 'y',
home: 'z'
    });
}

Please offer some code to show how you have tried to work with this.

  • Related