1

I have an array like this:

var json.result= [
{"id":"0","category":"Camera","name":"600D Kit", "condition":"OK"},    
{"id":"1","category":"Camera","name":"600D Kit", "condition":"missing cap"},        
{"id":"2","category":"Camera","name":"7D Kit", "condition":"OK"},
{"id":"3","category":"Camera","name":"7D Kit", "condition":"OK"}]

I am trying to do the following: 1/ Find all the "name" 2/ When found duplicated "name", print only the first object

So that the result would be:
equipment id: 0
category: Camera
name: 600D Kit

equipment id: 2
category: Camera
name: 7D Kit

The following is my attempt:

json.result.map(function(equipment){

    var equipmentNamesArray = equipment.name;
    var arr = $.makeArray(equipmentNamesArray);

    var uniqueNames = equipmentNamesArray.reduce(function(a,b){
        if (a.indexOf(b) < 0) a.push(b);    
    }, equipmentNamesArray);
    console.log("equipment ID: ", uniqueNames.id);
    console.log("category: ", uniqueNames.category);
    console.log("name: ", uniqueNames);     
});

However, I have an error of TypeError: equipmentNamesArray.reduce is not a function. I would appreciate very much if anyone could tell me which part of the logic have I done wrong please :)))

Cheers, Karen

1 Answer 1

1

Here is the code you need:

JSFiddle

var json = [], equipmentNamesArray = [];

json.result= [
{"id":"0","category":"Camera","name":"600D Kit", "condition":"OK"},    
{"id":"1","category":"Camera","name":"600D Kit", "condition":"missing cap"},        
{"id":"2","category":"Camera","name":"7D Kit", "condition":"OK"},
{"id":"3","category":"Camera","name":"7D Kit", "condition":"OK"}];

json.result.map(function(equipment) {
    if ($.inArray(equipment.name, equipmentNamesArray) === -1) {
      console.log(equipment);
      equipmentNamesArray.push(equipment.name);
    }
});

You have to create the equipmentNamesArray array to contain the items checked before everything else, when you start iterate the main result array you check if the equipment.name is already in the equipmentNamesArray array.

If it's not in the array print it and push it to the array.

Then the next one will be skipped because is contained in the equipmentNamesArray array yet.

Here is another version with a change to keep a new array with only the items you want: JSFiddle 2

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

1 Comment

Thank you very much for your explanation and JSFiddle is exactly what I need :))) Merci beaucoup x

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.