Related
First of all, any of built-in methods cannot be used. ex. pop(), shift(). What I can use is merely loops, array and so on.
I would like to make a function which takes an array as an argument and generate random strings of numbers, which does not contain these numbers given in the array.
For instance, func([6, 2]) //=> "20353" (2 and 6 would not be there).
The array length could change ([6, 2, 9], [7, 2, 1, 9]). So the function has to have an ability to accommodate any length of an array.
In order to tackle this practice question, I have used for and while loops. However, I ran into a problem that, when the second index is checked (whether numbers randomly generated contain 2 or not, in the example), if it contains, I regenerate the random number and it could produce the first index number (in this case, 6) which I do not want.
Please see the code I posted below and help me solve this. On top of that, if there is another way to get the same result which is a better way, please let me know too.
let str = "";
let arr = [];
let tem
const func = arg2 => {
for (let i = 0; i < 5; i++) {
arr[i] = Math.floor(Math.random() * 10);
}
for (let i = 0; i < arr.length; i++) {
for (let v = 0; v < arg2.length; v++) {
if (arg2[v] == arr[i]) {
do {
tem = Math.floor(Math.random() * 10);
} while (tem == arr[i])
arr[i] = tem;
}
}
}
for (let i = 0; i < arr.length; i++) str += arr[i]
return str
}
console.log(func([6, 2]))
// the output will not contain 2, which is the last index element
// however, when the second index number is removed, the output might replace it with 6, which is the first index element
Expected output:
func([6, 3, 8]) //=> "45102"
func([4, 9]) //=> "55108"
First, you already use two native methods (floor and random), but I'll assume you're OK with that.
Secondly, in your question the term digit would have been more appropriate in some instances than number. There is a difference...
To avoid that you still select a digit that is not allowed, you could first build an array with digits that are still allowed, and then randomly pick values from that array. That way you will not ever pick a wrong one.
Here is how that would look:
const func = arg2 => {
const digits = [0,1,2,3,4,5,6,7,8,9];
// Mark digits that are not allowed with -1
for (let i=0; i<arg2.length; i++) {
digits[arg2[i]] = -1;
}
// Collect digits that are still allowed
const allowed = [];
for (let i=0; i<digits.length; i++) {
if (digits[i] > -1) allowed[allowed.length] = digits[i];
}
// Pick random digits from the allowed digits
let str = "";
for(let i=0; i<5; i++) {
str += allowed[Math.floor(Math.random() * allowed.length)];
}
return str;
}
console.log(func([6, 2]));
Just for fun, if you lift the restrictions on what language aspects cannot be used, you can do this as follows:
const func = arg2 => {
const digits = new Set(Array(10).keys());
for (let digit of arg2) digits.delete(digit);
const allowed = [...digits];
return Array.from({length:5}, () =>
allowed[Math.floor(Math.random() * allowed.length)]
).join``;
}
console.log(func([6, 2]));
I suspect you're overthinking this. The basic algorithm is:
In a loop:
If output has 5 digits, return it.
Otherwise
Pick a random digit n from 0 to 9.
If n is not in the list of excluded numbers, it to output.
This maps pretty directly to the following function:
function fn(exclude, length = 5) {
let output = '';
while (output.length < length) {
const n = Math.floor(Math.random() * 10)
if (!exclude.includes(n)) {
output += n;
}
}
return output;
}
console.log(fn([6,3,8]));
There are, of course, other ways to achieve this, such as initializing an array with five elements and then joining the elements:
function fn(exclude, length = 5) {
return Array.from({ length }, () => {
let n;
while (n = Math.floor(Math.random() * 10), exclude.includes(n)) {}
return n;
}).join('');
}
console.log(fn([6,3,8]));
You need to loop through the entire arg2 array each time you pick a random digit. You can't replace the value in the arg2 loop, because then you won't check against earlier elements.
You don't need the arr array, you can append to str in the loop.
const func = arg2 => {
let str = "";
let arr = [];
for (let i = 0; i < 5; i++) {
let random;
while (true) {
let ok = true;
random = Math.floor(Math.random() * 10);
for (let j = 0; j < arg2.length; j++) {
if (random == arg2[j]) {
ok = false;
break;
}
}
if (ok) {
break;
}
}
str += random
}
return str
}
console.log(func([6, 2]))
Besides the fact (what others stated as well) that you use native array-methods yourself, I would probably go for it with something like this (using only what you used so far):
const func = without => {
let result = '';
while (result.length < 5) {
let rand = Math.floor(Math.random() * 10);
let add = true;
for (i=0; i<without.length; i++) {
if (rand === without[i]) {
add = false;
}
}
if (add) {
result += rand;
}
}
return result;
}
console.log(func([6, 2]))
a more concise version using native array methods could look like this:
const func = without => {
let result = '';
while (result.length < 5) {
let rand = Math.floor(Math.random() * 10);
if (!without.includes(rand)) {
result += rand;
}
}
return result;
}
console.log(func([6, 2]))
Very new, trying to make a function that takes out and separates all negatives/positives/zeros in an array. So far Ive been able to make an acceptable for loop but only with hard coded numbers. Dont currently know how to convert it into a function. please help.
var arr=[1,3,5,-9,-3,0];
var new_arr = [];
var new_arr2 = [];
var new_arr3=[];
for(i =0; i < arr.length; i++){
if(arr[i]>0){
new_arr.push(arr[i]);
}
else if(arr[i]<0){
new_arr2.push(arr[i]);
}
else if(arr[i]===0){
new_arr3.push(arr[i]);
}
}
console.log(new_arr3.length/arr.length);
console.log(new_arr2.length/arr.length);
console.log(new_arr.length/arr.length);
How about something like this?
function division(arr) {
var new_arr = [];
var new_arr2 = [];
var new_arr3 = [];
for (i = 0; i < arr.length; i++) {
if (arr[i] > 0) {
new_arr.push(arr[i]);
} else if (arr[i] < 0) {
new_arr2.push(arr[i]);
} else if (arr[i] === 0) {
new_arr3.push(arr[i]);
}
}
console.log(new_arr3.length / arr.length);
console.log(new_arr2.length / arr.length);
console.log(new_arr.length / arr.length);
}
division([1, 3, 5, -9, -3, 0]);
This new function takes the array as a parameter, so all you need to do is call it and pass the array.
You can try this way also, here I am considering 0 as a positive number. If you want, you can tweak the condition as per requirement.
function positive_negative(array ){
positive = array.filter(function (a) { return a >= 0; });
negative = array.filter(function (a) { return a < 0; });
return [positive,negative];
}
var array = [1,3,5,-9,-3,0];
console.log(positive_negative(array));
I can't figure out why the following code does not work for the Coderbyte challenge where you have to test a string to see if it is a palindrome (the characters being the same when read in reverse as they are normally). I know there are better ways to write the code for the same result, but I still think this way should work (assuming no capital letters or non-alphabetic characters in the input string). But testing it doesn't yield the results I need. Here it is:
function Palindrome(str) {
var myArray = str.split("");
for(var i = 0; i < myArray.length; i++) {
if(myArray[i] === " ") {
myArray.splice(i, 1);
}
}
var firstHalf = myArray.slice(0, Math.floor(myArray.length/2));
var secHalf = myArray.slice(Math.ceil(myArray.length/2));
secHalf.reverse();
if(firstHalf === secHalf) {
return true;
}
return false;
}
What I'm trying to do is split up the input string into an array, remove the spaces, specify the first and second halves of that array, reverse the second half, then compare if the two halves are equal. In cases where the number of characters in the string str is odd the middle character isn't taken into account since it shouldn't matter. And I did try asking this on Coderbyte but my question was not posted for some reason.
You can't do the array comparison using === since that checks if the object references are equal (the variable refers to the same array).
For example:
var a = [1, 2, 3];
var b = [1, 2, 3];
var c = a;
a === a; // true
a === b; // false
a === c; // true
You should check through the array contents by looping:
function Palindrome(str) {
var myArray = str.split("");
for(var i = 0; i < myArray.length; i++) {
if(myArray[i] === " ") {
myArray.splice(i, 1);
}
}
var firstHalf = myArray.slice(0, Math.floor(myArray.length/2));
var secHalf = myArray.slice(Math.ceil(myArray.length/2));
secHalf.reverse();
for (var i = 0; i < firstHalf.length; i++){
if (firstHalf[i] != secHalf[i]) return false;
}
return true;
}
You are comparing two arrays directly with ===. That won't work. First join them into strings:
var myArray = str.split("");
for(var i = 0; i < myArray.length; i++) {
if(myArray[i] === " ") {
myArray.splice(i, 1);
}
}
var firstHalf = myArray.slice(0, Math.floor(myArray.length/2));
var secHalf = myArray.slice(Math.ceil(myArray.length/2));
secHalf.reverse();
// join them like this
firstHalf = firstHalf.join('');
secHalf = secHalf.join('');
return firstHalf === secHalf;
If you want shorter/simpler/faster way to do this, try:
function Palindrome(str) {
str = str.replace(/ /g, '');
return str == str.split('').reverse().join('');
}
So I tried looking for this in the search but the closest I could come is a similar answer in several different languages, I would like to use Javascript to do it.
The problem is I have an arbitrary string that I would like to return the first non repeating character. EX: 'aba' -> would return b
'aabcbd' -> would return c.
This is what I have so far, just a simple for loop to start.
var someString = 'aabcbd';
var firstNonRepeatedCharacter = function(string) {
for(var i = 0; i < someString.length; i++){
}
};
http://jsfiddle.net/w7F87/
Not sure where to go from here
You can use the indexOf method to find the non repeating character. If you look for the character in the string, it will be the first one found, and you won't find another after it:
function firstNonRepeatedCharacter(string) {
for (var i = 0; i < string.length; i++) {
var c = string.charAt(i);
if (string.indexOf(c) == i && string.indexOf(c, i + 1) == -1) {
return c;
}
}
return null;
}
Demo: http://jsfiddle.net/Guffa/Se4dD/
If you're looking for the first occurrence of a letter that only occurs once, I would use another data structure to keep track of how many times each letter has been seen. This would let you do it with an O(n) rather than an O(n2) solution, except that n in this case is the larger of the difference between the smallest and largest character code or the length of the string and so not directly comparable.
Note: an earlier version of this used for-in - which in practice turns out to be incredibly slow. I've updated it to use the character codes as indexes to keep the look up as fast as possible. What we really need is a hash table but given the small values of N and the small, relative speed up, it's probably not worth it for this problem. In fact, you should prefer #Guffa's solution. I'm including mine only because I ended up learning a lot from it.
function firstNonRepeatedCharacter(string) {
var counts = {};
var i, minCode = 999999, maxCode = -1;
for (i = 0; i < string.length; ++i) {
var letter = string.charAt(i);
var letterCode = string.charCodeAt(i);
if (letterCode < minCode) {
minCode = letterCode;
}
if (letterCode > maxCode) {
maxCode = letterCode;
}
var count = counts[letterCode];
if (count) {
count.count = count.count + 1;
}
else {
counts[letterCode] = { letter: letter, count: 1, index: i };
}
}
var smallestIndex = string.length;
for (i = minCode; i <= maxCode; ++i) {
var count = counts[i];
if (count && count.count === 1 && count.index < smallestIndex) {
smallestIndex = count.index;
}
}
return smallestIndex < string.length ? string.charAt(smallestIndex) : '';
}
See fiddle at http://jsfiddle.net/b2dE4/
Also a (slightly different than the comments) performance test at http://jsperf.com/24793051/2
var firstNonRepeatedCharacter = function(string) {
var chars = string.split('');
for (var i = 0; i < string.length; i++) {
if (chars.filter(function(j) {
return j == string.charAt(i);
}).length == 1) return string.charAt(i);
}
};
So we create an array of all the characters, by splitting on anything.
Then, we loop through each character, and we filter the array we created, so we'll get an array of only those characters. If the length is ever 1, we know we have a non-repeated character.
Fiddle: http://jsfiddle.net/2FpZF/
Two further possibilities, using ECMA5 array methods. Will return undefined if none exist.
Javascript
function firstNonRepeatedCharacter(string) {
return string.split('').filter(function (character, index, obj) {
return obj.indexOf(character) === obj.lastIndexOf(character);
}).shift();
}
console.log(firstNonRepeatedCharacter('aabcbd'));
On jsFiddle
Or if you want a bit better performance, especially on longer strings.
Javascript
function firstNonRepeatedCharacter(string) {
var first;
string.split('').some(function (character, index, obj) {
if(obj.indexOf(character) === obj.lastIndexOf(character)) {
first = character;
return true;
}
return false;
});
return first;
}
console.log(firstNonRepeatedCharacter('aabcbd'));
On jsFiddle
I came accross this while facing similar problem. Let me add my 2 lines.
What I did is a similar to the Guffa's answer. But using both indexOf method and lastIndexOf.
My mehod:
function nonRepeated(str) {
for(let i = 0; i < str.length; i++) {
let j = str.charAt(i)
if (str.indexOf(j) == str.lastIndexOf(j)) {
return j;
}
}
return null;
}
nonRepeated("aabcbd"); //c
Simply, indexOf() gets first occurrence of a character & lastIndexOf() gets the last occurrence. So when the first occurrence is also == the last occurence, it means there's just one the character.
Here's a Solution using Regex to replace all repeating characters and then returning the first character.
function firstNonRepeat(str) {
// Sorting str so that all repeating characters will come together & replacing it with empty string and taking first character using substr.
var rsl = str.split('').sort().join('').replace(/(\w)\1+/g,'').substr(0,1);
if(rsl) return rsl;
else return 'All characters are repeated in ' + str;
}
console.log(firstNonRepeat('aaabcccdeeef'));
console.log(firstNonRepeat('aaacbdcee'));
console.log(firstNonRepeat('aabcbd'));
First of all, start your loop at 1, not 0. There is no point in checking the first character to see if its repeating, obviously it can't be.
Now, within your loop, you have someString[i] and someString[i - 1]. They are the current and previous characters.
if someString[i] === someString[i - 1] then the characters are repeating, if someString[i] !== someString[i - 1] then they are not repeating, so you return someString[i]
I won't write the whole thing out for you, but hopefully the thought process behind this will help
function FirstNotRepeatedChar(str) {
var arr = str.split('');
var result = '';
var ctr = 0;
for (var x = 0; x < arr.length; x++) {
ctr = 0;
for (var y = 0; y < arr.length; y++) {
if (arr[x] === arr[y]) {
ctr+= 1;
}
}
if (ctr < 2) {
result = arr[x];
break;
}
}
return result;
}
console.log(FirstNotRepeatedChar('asif shaik'));
Here's an O(n) solution with 2 ES6 Sets, one tracking all characters that have appeared and one tracking only chars that have appeared once. This solution takes advantage of the insertion order preserved by Set.
const firstNonRepeating = str => {
const set = new Set();
const finalSet = new Set();
str.split('').forEach(char => {
if (set.has(char)) finalSet.delete(char);
else {
set.add(char);
finalSet.add(char);
}
})
const iter = finalSet.values();
return iter.next().value;
}
let arr = [10, 5, 3, 4, 3, 5, 6];
outer:for(let i=0;i<arr.length;i++){
for(let j=0;j<arr.length;j++){
if(arr[i]===arr[j+1]){
console.log(arr[i]);
break outer;
}
}
}
//or else you may try this way...
function firstDuplicate(arr) {
let findFirst = new Set()
for (element of arr)
if (findFirst.has(element ))
return element
else
findFirst.add(element )
}
function firstUniqChar(str) {
let myMap = new Map();
for(let i = 0; i < str.length; i++) {
let char = str.charAt(i);
if(!myMap.has(char)) {
myMap.set(char, 0);
}
myMap.set(char, myMap.get(char) + 1 );
}
for(let [key, value] of myMap) {
if(value === 1) {
return key;
}
}
return null;
}
let result = firstUniqChar("caabbdccee");
console.log(result);
You can use Map Object and set key and value, where in value you store the count for that particular character, After that you can iterate over map and check where is value 1 and return that key.
Map Object remembers the original insertion order of the keys.
This solution should works with array with integers and string.
function firstNoneRepeating(list, map = new Map()) {
for (let item of list) {
if (map.has(item)) {
map.set(item, map.get(item) + 1);
} else {
map.set(item, 1);
}
}
for (let [key, value] of map.entries()) {
if (value === 1) {
return key;
}
}
}
console.log(firstNoneRepeating("aabcbd"));
console.log(firstNoneRepeating([5, 2, 3, 4, 2, 6, 7, 1, 2, 3]));
let str='aabcbd'
let ans=''
for (let i=0;i<str.length;i++){
if(str.indexOf(str.charAt(i))===str.lastIndexOf(str.charAt(i))){
ans+=str.charAt(i)
break
}
}
console.log(ans)
Fill an empty array with zeros, with same length as the string array, and tally up how many times they appear through the loop. Grab the first one in the tallied array with a value of 1.
function firstNotRepeatingCharacter(s) {
const array = s.split("");
let scores = new Array(array.length).fill(0);
for (let char of array) {
scores[array.indexOf(char)]++;
}
const singleChar = array[scores.indexOf(1)];
return singleChar ? singleChar : "_"
}
You can iterate through each character to find() the first letter that returns a single match(). This will result in the first non-repeated character in the given string:
const first_nonrepeated_character = string => [...string].find(e => string.match(new RegExp(e, 'g')).length === 1);
const string = 'aabcbd';
console.log(first_nonrepeated_character(string)); // c
Here is my solution which have time complexity of o(n)
function getfirstNonRepeatingCharacterInAString(params) {
let count = {};
for (let i = 0; i < params.length; i++) {
let count1 = 0;
if (!count[params.charAt(i)]) {
count[params.charAt(i)] = count1 + 1;
}
else {
count[params.charAt(i)] = count[params.charAt(i)] + 1;
}
}
for (let key in count) {
if (count[key] === 1) {
return key;
}
}
return null;
}
console.log(getfirstNonRepeatingCharacterInAString("GeeksfoGeeks"));
Here is my solution using forEach and convert the string into an array
function firstNotRepeatingCharacter(s) {
var strArr = s.split("");
var found = "_";
strArr.forEach(function(item, index) {
if (strArr.indexOf(item) == index && strArr.indexOf(item, index + 1) == -1) {
if (found === "_") {
found = item;
}
}
})
return found;
}
firstNotRepeatingCharacter("abacabad")
Here is another approach:
Everytime you find equal chars store it in an array and break out of the loop. If the char is not found in the array then you have your first nonRepeating char
function nonRepeatingChars(value) {
const memory = []
for (let i = 0; i < value.length; i++) {
for (let j = i + 1; j < value.length; j++) {
if (value[i] === value[j]) {
memory.push(value[j])
break;
}
}
if (!memory.some(x => x === value[i])) {
return value[i];
}
}
return "all chars have duplicates";
}
console.log('First non repeating char is:',nonRepeatingChars("esen"))
console.log('First non repeating char is:',nonRepeatingChars("esesn"))
console.log('First non repeating char is:',nonRepeatingChars("eseulsn"))
console.log('First non repeating char is:',nonRepeatingChars("esesnn"))
> var firstNonRepeatedCharacter = function (str){
> for(i=0;i<str.length;i++){
> if(str.indexOf(str.charAt(i)) === str.lastIndexOf(str.charAt(i))){
> console.log(str.charAt(i));
> break;
> } } }
>
> firstNonRepeatedCharacter ("areerak");
you can check below link
https://codepen.io/t3veni/pen/wvvxJzm
Easy way to solve this algorithm, very straight forward.
function firstNonRepeatChar(str){
let map = {};
for(let i=0; i<str.length; i++){
if(Object.keys(map).includes(str[i])){
map[str[i]]++
}
else{
map[str[i]] = 1;
}
}
for(let j=0; j< Object.values(map).length; j++){
if(Object.values(map)[j] == 1){
console.log(Object.keys(map)[j]);
return
}
if (j == Object.values(map).length-1 && Object.values(map)[j] != 1){
console.log('_');
return;
}
else{
continue;
}
}
}
nonRepeat("aaabbcccdeeef");
Here is one other solution just using array, using 26 unique character as length of array:
var firstUniqChar = (function(s) {
var arr = [];
var str = s.toLowerCase();
for(let c of str){
let index = c.charCodeAt(0) - "a".charCodeAt(0);
arr[index]? ++arr[index]: arr[index]=1;
}
for(let c of str){
let index = c.charCodeAt(0) - 97;
if(arr[index] == 1){
return c;
};
}
return -1;
}("aabcbd"));
console.log(firstUniqChar);
We can keep track of frequency of each character of the string in an object.
For example : for "aabcbd" we can store the frequency as
{ "a":2, "b":2, "c":1, "d":1 }
This will take O(n) time.
Then we can traverse over this object and find the first character with frequency 1, which will also take O(n) time. So, the time complexity for this approach will be O(n).
const firstNonRepeating=(str)=>{
const obj={};
str.split("").forEach(item=>{
obj[item]
? obj[item]++
: obj[item]=1;
});
const item = Object.keys(obj).find(key=> obj[key] === 1);
return item;
}
Note: I use ES6 Object.keys method which may not work in older
browsers.
//To find first non repeating letter
//It will check for both upper and lower case
//only use one String.indexOf()
var mystr="ohvhvtccggt";
var checkFirstNonRepeating=function(){
var ele=[];
for(var i=0;i<mystr.length;i++) {
var key=mystr.charAt(i);
if(!ele[key])
ele[key]=0;
ele[key]++;
//Just check for second occurance of character
//no need to use indexOf twice
if(mystr.indexOf(key,i+1)==-1 && ele[key]<2)
return mystr[i];
}
return "All repeating letters";
}
console.log(checkFirstNonRepeating());
/*
Input : "ohvhvtoccggt"
Output : All repeating letters
Input :"oohjtht"
Output :j
*/
I used object to keep track of characters count in a string then return the char that has the fa value of 1. Here is a demo:
function firstNotRepeatingCharacter(s) {
// initialize an empty object to store chars
let seen = {};
let letter = '';
// iterate over each char in a string
// if it is already there increase value by one
// else set the value to 1
for(let char of s){
if (seen[char]){
seen[char] +=1;
} else {
seen[char] = 1;
}
}
// iterate over the new constructed object
// if the value is 1 and the output variable is empty
// return the associated key to the value 1
// else return '_'
for(let v in seen){
while(seen[v] == 1 && letter === ''){
letter += v;
return letter;
}
}
return('_');
}
console.log(firstNotRepeatingCharacter("abacabad"));
console.log(firstNotRepeatingCharacter("cbc"));
console.log(firstNotRepeatingCharacter("bcccccccccccccyb"));
console.log(firstNotRepeatingCharacter("aaa"));
The most satisfactory and easy to understand answer is the following.
function firstNotRepeatingCharacter(s) {
const arr = s.split("");
for(let i = 0; i < arr.length; i++){
let chr = arr[i];
if( arr.indexOf(arr[i]) == arr.lastIndexOf(arr[i])){
return arr[i]
}
}
return "_"
}
Explanation: It loops through all the characters of a string from forward and backward and then compares the values. If the index of both forward and backward search is true then it returns that character.
let str = 'aabbcdd';
let val = str.split('').reduce((a, e)=>{ if(str.indexOf(e) == str.lastIndexOf(e)) {a = e }; return a})
console.log(val); // c
the implementation below has a good time complexity and it accounts for letters with different cases:
steps
must touch every character in the string to know if it's repeated or not
function firstNonRepeatingLetter(wordd) {
const chars = {}
let word = wordd.toLowerCase()
// go through chars
// store chars in hash with values of array storing index of char and true if only 1 encountered so far
for (let i = 0; i < word.length; i += 1) {
let char = word[i]
if (chars[char]) {
chars[char][0] = false
} else {
chars[char] = [true, i]
}
}
let output = ''
let index;
for (let key in chars) {
// return char with true and lowest index
if (chars[key][0]) {
index = index === undefined ? chars[key][1] : index
if (index >= chars[key][1]) {
output = key
}
}
}
return index === undefined ? '' : wordd[index]
}
console.log(firstNonRepeatingLetter('sTreSS')) //T```
The bellow solution is a kind of frequency counter pattern and it will run only one loop, so O(n) will be the time complexity.
function firstNotRepeatingCharacter(str) {
const obj = {};
for (let i = 0, L = str.length; i < L; i++) {
const char = str[i];
obj[char] = obj[char] ? obj[char] + 1 : 1;
}
for (let key of Object.keys(obj)) {
if (obj[key] == 1) {
return key;
}
}
return -1;
}
Here is another solution
function firstNotRepeatingCharacter(s) {
const obj = {};
for (let i of s) {
if(!obj[i]) {
obj[i] = 1;
} else if (obj[i]) {
obj[i] = +obj[i] + 1;
}
}
for (let [key, value] of Object.entries(obj)) {
if(value == 1) return key;
}
return "_"
}
Using below method can achieve first non repeated character
function main(str) {
str = String(str).toLowerCase();
let non_repeated_char = 'N/A';
for (let i = 0; i < str.length; i++) {
let currentChar = str[i];
let repeated_times = String(str).split('').filter(e => e == currentChar).length;
if (repeated_times === 1) {
non_repeated_char = currentChar;
break;
}
}
return non_repeated_char;
};
let Result = main("basketball");
console.log("The Non Repeated char is-->", Result);
Assume we have a string like the following :
,34,23,4,5,634,23,12,5,4,3,1234,23,54,,,,,,,123,43,2,3,4,5,3424,,,,,,,,123,,,1234,,,,,,,45,,,56
How can we convert it to the following string with RegExp in Javascript ?
34,23,4,5,634,12,3,1234,54,123,43,2,3424,45,56
Actually, I wanna remove repeated items and first and last , char
[edited] To turn these into a set of unique numbers, as you are actually asking for, do this:
function scrapeNumbers(string) {
var seen = {};
var results = [];
string.match(/\d+/g).forEach(function(x) {
if (seen[x]===undefined)
results.push(parseInt(x));
seen[x] = true;
});
return results;
}
Demo:
> scrapeNumbers(',1,22,333,22,,333,4,,,')
[1, 22, 333, 4]
If you had an Array.prototype.unique() primitive, you could write it like so in one line:
yourString.match(/\d+/g).map(parseBase10).unique()
Unfortunately you need to be a bit verbose and define your own parseBase10 = function(n){return parseInt(n)} due to this ridiculous hard-to-track-down bug: javascript - Array#map and parseInt
No need for regex. Few tricks
text = ',34,23,4,5,634,23,12,5,4,3,1234,23,54,,,,,,,123,43,2,3,4,5,3424,,,,,,,,123,,,1234,,,,,,,45,,,56';
text = text.replace(/,+/g, ','); //replace two commas with one comma
text = text.replace(/^\s+|\s+$/g,''); //remove the spaces
textarray = text.split(","); // change them into array
textarray = textarray.filter(function(e){ return e.length});
console.log(textarray);
// Now use a function to make the array unique
Array.prototype.unique = function(){
var u = {}, a = [];
for(var i = 0, l = this.length; i < l; ++i){
if(this[i] in u)
continue;
a.push(this[i]);
u[this[i]] = 1;
}
return a;
}
textarray = textarray.unique();
text = textarray.join(','); //combine them back to what you want
console.log(text);
Demo
If you are familier with jQuery
text = text.replace(/,+/g, ',');
text = $.trim(text);
text = $.unique(text.split(",")).filter(function(e){ return e.length}).join(",");
console.log(text);
Demo
This will do it:
function arrIndex(fnd, arr) {
for (var len = arr.length, i = 0; i < len; i++) {
if (i in arr && arr[i] === fnd) {
return i;
}
}
return -1;
}
function scrapeNumbers(str) {
var arr = str.replace(/,+/g, ",").replace(/^,/, "").replace(/,$/, "").split(",");
for (var i = 0, len = arr.length, rtn = []; i < len; i++) {
if (i in arr && arrIndex(arr[i], rtn) == -1) {
rtn.push(arr[i]);
}
}
return rtn.join(",");
}
var str = ",,34,23,4,5,634,23,12,5,4,3,1234,23,54,,,,,,,123,43,2,3,4,5,3424,,,,,,,,123,,,1234,,,,,,,45,,,56,,";
alert(scrapeNumbers(str));
Here is a jsFiddle
Note: I created a custom array.indexOf function for a better browser support