Tyra Pululi
Tyra Pululi

Reputation: 446

Remove part of string after character in an array and remove repeated elements

I'm trying to remove part of the value of an element in an array after '_' and once its done remove all repeated elements.

Array looks like

names =  ["ann_w", "james_q", "ann_q", "peter_p", "steve_q", "james_s"];

And I am trying to convert it into

names = ["ann", "james", "peter", "steve"];

Below code is returning undefined and cant figure it out how to remove all repeated elements.

for (i = 0; i < names.length; i++) {
   names[i] = names[i].substring(names[i].indexOf("_") + 1);
}

Upvotes: 1

Views: 720

Answers (6)

hirakJS
hirakJS

Reputation: 109

var names = ["ann_w", "james_q", "ann_q", "peter_p", "steve_q", "james_s"];

var tmp = names.map(function(n){
   return n.split("_")[0];
}).sort();

// tmp = ["ann", "ann", "james", "james", "peter", "steve"]

var result = [];

tmp.forEach(function(t){
    if(!result.includes(t))
        result.push(t);
});

console.log(result);

Upvotes: 2

Sanjay Gupta
Sanjay Gupta

Reputation: 25

names =  ["ann_w", "james_q", "ann_q", "peter_p", "steve_q", "james_s"];

for (i = 0; i < names.length; i++) {
   names[i] = names[i].substring(0, names[i].indexOf("_"));
}

var unique = names.filter(function(item, i, names) {
    return i == names.indexOf(item);
});

console.log(unique)

Upvotes: 0

me_
me_

Reputation: 743

var names =  ["ann_w", "james_q", "ann_q", "peter_p", "steve_q", "james_s"];
var finalArray = [];
for (var i = 0; i <names.length; i++){
var substringArray = names[i].split("_");
if(finalArray.indexOf(substringArray[0]) == -1) finalArray.push(substringArray[0]);
}

https://jsfiddle.net/3z3naanb/9/

Upvotes: 0

Pankaj Shukla
Pankaj Shukla

Reputation: 2672

You can do this: Use array#reduce and Object.keys. reduce will create an object with name as keys and then you can get the key as an array via Object.keys().

var names =  ["ann_w", "james_q", "ann_q", "peter_p", "steve_q", "james_s"];

var obj = names.reduce(function(r,v) {
  var name = v.split('_')[0];
  if(!r[name]) {
    r[name] = 1;
  }
  return r;
}, {});

console.log(Object.keys(obj));

Upvotes: 0

Michał Sałaciński
Michał Sałaciński

Reputation: 2266

use Set & map:

var names =  ["ann_w", "james_q", "ann_q", "peter_p", "steve_q", "james_s"];

var unique_names = [ ...new Set(names.map(name => {
   return name.split('_')[0]
}))]
console.log(unique_names)

Upvotes: 4

CBredlow
CBredlow

Reputation: 2840

You can try using split on the string instead of doing the substring, then you'd get an array of strings, and since you only want the first name, you'd take array[0].

Also, you're getting back errors because you're trying to substring the entire array instead of a string. You'd need to do names[i] = names[i].substring

Upvotes: 0

Related Questions