Arun
Arun

Reputation: 557

Replace duplicate array object value with another in javascript

var indianTeam = [{
      firstName: "KL",
      lastName: "Rahul"
    }, {
      firstName: "Jayant",
      lastName: "Yadav"
    }, {
      firstName: "Umesh",
      lastName: "Yadav"
    }];

In above array, you can find lastname in 2nd and 3rd have duplicate values "yadav" so I want to find second duplicate (i.e umesh yadav) and replace it with its first name, leaving jayant yadav as unique.

Function I used so far

services.filterPlayers = function() {

  var i,j,tempArray = [];  

  for (i = 0; i < indianTeam.length; i++) {
      tempArray.push(indianTeam[i].lastName);
  }

  tempArray = tempArray.filter(function(elem, pos){
    if (tempArray.indexOf(elem) !== pos) {
      return true;
    }     
  });

  return tempArray;
};

Scenario one: I filtered out duplicate yadav and returned unique values to temporary with == condition signs,

Scenario two: only yadav returned to temporary with !== condition

How to replace duplicate yadav with firstname and push to same position in temporary array?

Reference : codepen link

Upvotes: 1

Views: 2265

Answers (2)

Jonas Wilms
Jonas Wilms

Reputation: 138234

This gives you a unique lastName array:

new Set(indianTeam.map(el=>el.lastName));

This creates a unique lastName, fallback firstName array:

indianTeam=indianTeam.map((el,i)=>indianTeam.findIndex(e=>e.lastName==el.lastName)===i?el.lastName:el.firstName);

http://jsbin.com/sozeficafa/edit?console

You could use the map function wich replaces each element by the returned one. The code checks if the Element is the first found, if so it keeps it, if not it replaces it by the first.

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386522

You could use a hash table for the lastNameand check if set. If set, then take firstName, otherwise lastName.

var indianTeam = [{ firstName: "KL", lastName: "Rahul" }, { firstName: "Jayant", lastName: "Yadav" }, { firstName: "Umesh", lastName: "Yadav" }, { firstName: "jane" }, { firstName: "joe" }],
    hash = Object.create(null),
    result = indianTeam.map(function (a) {
        if (!a.lastName || hash[a.lastName]) {
            return a.firstName;
        }          
        hash[a.lastName] = true;
        return a.lastName;
    });

console.log(result);

Upvotes: 1

Related Questions