javascript onBlur to to avoid duplicate string - javascript

In my project I need onBlur event to check string have contain any duplicate character to remove it i.e text value has 01,02,04,01,07,2 in the String after the comma 01 has to duplicate value so I need 01,02,04,07,2. Is this possible?

$("input:text").on('blur', function() {
var textVal = $(this).val();
var valArray = textVal.split(',');
var newValArray = [];
for(var i in valArray) {
if(newValArray.indexOf(i) === -1) {
newValArray.push(i);
}
}
var newTextVal = newValArray.join();
$(this).val(newTextVal);
})

Using JQuery you could do that
var numberString = '01,02,04,01,07,2';
var result = [];
$.each(numberString.split(','), function(index, number) {
if($.inArray(number, result) === -1) {
result.push(number);
}
});
document.write(result.join(','));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You can use the split(",") method to create an array of the values and then loop through the array values and then use splice(0,1) method to remove the duplicate. After that you can revert the array back to a string using the join(",") method to create the string with the comma delimiter.

I wrote this reduce codes. It does what you need.
//I altered your number string to this.
var numberString = '01,02,04,01,07,2,07,10,55,55,10,02,500,450';
var strDedoop = function ( str ) {
var strArr = [], // temp array
numStrSplit = str.split(','); // split the number string by comma
//loop through the array
numStrSplit.forEach(function(currentValue) {
// Ternary operation. If the number is not in the array it is put in.
strArr.indexOf(currentValue) === -1 ? strArr.push(currentValue) : false;
});
return strArr.toString(); // return the array as a string.
}
strDedoop(numberString);
// returns "01,02,04,07,2,10,55,500,450"
You can use it this way.
$("input:text").on('blur', strDedoop(numberString));

Related

How to check if any of the strings from an array with variable length are present in another string?

I am trying to filter some data from an array in a JSON file, based on an input of the form string1, string1,string2, string1,string2,string3 etc., that is, some strings separated by a ,.
What I'm trying to do:
let arrInput = document.getElementById('inputBox').val.split(',');
for(let i = 0; i < arrToFilter.length; i++){
if(.........what to write here?...........){
arrOutput.push(arrToFilter[i]);
}
}
return arrOutput;
If the arrInput had a fixed length, I could accomplish this using indexOf != -1 for each element in arrInput, but here, since the length of arrInput is variable, how can I check if at least one of the strings present in arrInput is also present as a substring in arrToFIlter[i]?
Edit:
Example:
Let arrToFilter be ["abcqwer", "pizza", "definition", "abcdef", "example"]
Case 1 :
Say the input entered (in an <input> element) is abc,def.
For this, the arrOutput should be ["abcqwer", "definition", "abcdef"]
Case 2:
Say the input entered is abc
Expected output : ["abcqwer", "abcdef"]
Simple way is using some and filter,
var string = 'ad,kk,sb';
var array = ['adik', 'klop', 'pp'];
var stringers = string.split(',');
var result = array.filter((arr) => {
var isPresent = stringers.some(stringer => arr.includes(stringer));
return isPresent ? true : false;
});
console.log(result);
You need to iterate both arrays
let arrToFilter = ['abcqwer', 'pizza', 'definition', 'abcdef', 'example'];
let arrOutput = [];
let arrInput = document.getElementById('inputBox').value.split(',');
arrToFilter.forEach(filter => {
arrInput.forEach(input => {
if (!!input && filter.includes(input)) {
arrOutput.push(filter);
}
});
});
// distinct the output
return arrOutput.filter((v, i, a) => i === a.indexOf(v));

save and display an array of JSON/JS object(name/value pair) value as a comma separated string

var obj = {
aray1:[1,2],
aray2:["a","b"],
aray3:["ab","abab"]
};
this is the object i have values and i want to store the above array values as as a comma separated string and display as comma separated string on UI.
DB used is Mongo.
I think you are looking for a join method on arrays.
What you can do is obj.aray1.join(",") which will return 1,2 that you can display in your UI
As #eddyP23 mentioned, [].join will do the job for you.
var obj = {
aray1:[1,2],
aray2:["a","b"],
aray3:["ab","abab"]
};
var result = "";
for(key in obj){
result += ","+obj[key].join(",")
}
console.log(result.substring(1));
var obj = {
aray1:[1,2],
aray2:["a","b"],
aray3:["ab","abab"]
};
var a = Object.keys(obj).map(function(key){
return obj[key]
})
console.log(a.toString())

How to remove partial duplicate values in jquery array

I have a single level array of key/value pairs, like this:
var user_filters= ['color=blue', 'size=small', 'shape=circle', 'size=large', 'shape=square']
I need a function to perform the following:
find all duplicate keys
replace the first occurrence of the key/value pair with the second occurrence
delete the second occurrence
In this case, it would produce the following result:
user_filters= ['color=blue', 'size=large', 'shape=square']
Something like...
function update_array(){
$.each(user_filters, function(i){
var key = this.split('=')[0];
if(key is second occurrence in user_filters)
{
var index = index of first occurrence of key
user_filters[index] = user_filters[i];
user_filters.splice(i,1);
}
});
}
What is the best way to do this? Thanks!
I would keep the data in an object and this way any duplicate will automatically overwrite the previous entry..
See this for example:
var user_filters= ['color=blue', 'size=small', 'shape=circle', 'size=large', 'shape=square'];
var object = {};
for (var i = 0; i < user_filters.length; i++) {
var currentItem = user_filters[i].split('=');
var key = currentItem[0];
var value = currentItem[1];
object[key] = value;
}
console.log(object);
You can use a hash object to get the key-value pairs without duplicates and then transform the hash object back into an array like this:
function removeDuplicates(arr) {
var hash = arr.reduce(function(h, e) {
var parts = e.split("=");
h[parts[0]] = parts[1];
return h;
}, {});
return Object.keys(hash).map(function(key) {
return key + "=" + hash[key];
});
}
var user_filters = ['color=blue', 'size=small', 'shape=circle', 'size=large', 'shape=square'];
console.log(removeDuplicates(user_filters));
You could use a Map which does the unique/overriding automatically, and is able to get you an array back in case you need it
var user_filters= ['color=blue', 'size=small', 'shape=circle', 'size=large', 'shape=square'];
var m = new Map(user_filters.map(v => v.split("=")));
console.log([...m.entries()].map(v => v.join("=")));
It would be better to iterate from back of array ,
thus for every unique key you need to keep a variable true or false (initially false).
so if true mean already occurred so deleted it else keep it and make its variable true .
It is much more better approach then your current . you don't have to keep last index and swapping then deleting.
You may convert to json and then back to the array format you want . IN the below code you get the result object in the format you want.
var user_filters= ['color=blue', 'size=small', 'shape=circle', 'size=large', 'shape=square'];
function toJson(obj){
var output = {};
$.each(obj, function(i){
var keyvalPair = this.split('=')
var key = keyvalPair[0];
output[key]= keyvalPair[1];
});
return output;
}
function toArray(obj){
var output = [];
$.each(obj, function(i){
output.push(i+"="+obj[i]);
});
return output;
}
var result = toArray(toJson(user_filters));
console.log(result);

How to check if a string contains all the elements of an array in Javascript

I have a string apple_mango_banana and an array containing [apple,mango].
I want to check if my string contains all of the elements present in the array, if so, I want to show a div with the same ID as my string.
Use every() function on the arr and includes() on the str;
Every will return true if the passed function is true for all it's items.
var str = 'apple_mango_banana';
var arr = ['apple','banana'];
var isEvery = arr.every(item => str.includes(item));
console.log(isEvery);
You should use Array.every for such cases.
var s = "apple_mango_banana";
var s1 = "apple_mago_banana";
var fruits = ["apple","mango"];
var allAvailable = fruits.every(function(fruit){
return s.indexOf(fruit)>-1
});
var allAvailable1 = fruits.every(function(fruit){
return s1.indexOf(fruit)>-1
});
console.log(allAvailable)
console.log(allAvailable1)
var string="ax_b_c_d";
var array=['b','c','ax','d'];
var arr=string.split("_");
if(array.sort().join("")==arr.sort().join("") && arr.length==array.length)
{
console.log("match");
}

Removing an element from a javascript array causing issues

So I'm a little stuck as to why this isn't working. I'm trying to remove all of the empty strings in an array and it keeps giving me back an array that is just one empty string. Any ideas?
function splitNames(){
var names = document.getElementById("1").value.split("\n");
for(var i = 0; i<=names.length; i++){
if(names[i]==""){
names = names.splice(i, 1);
console.log(names);
}
}
console.log(names);
}
The string would look like this by the way.
Hi
Hello
(remove this one)
Bonjour
blah
(remove this one)
(remove this one)
blah
The array comes out to this ["Hi", "Hello","",...]
Perhaps the simplest way to do this is to use the filter function and search for truthy values. By default, empty strings are false.
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
var strings = ["zebras", "trees", "forests", "", "hi", "wizards", "", "", "lizards"];
strings = strings.filter((e) => e);
console.log(strings);
It's important to note that empty strings by default are false. However, strings that contain only whitespace characters are true. In that scenario, my example would not work and you would have to do this
strings.filter((e) => e.trim());
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
function splitNames(){
// var names = document.getElementById("1").value.split("\n");
var names = "Hi\nHello\n \nGoodBye".split("\n");
var filteredNames = names.filter(function(item){
return item.trim() !== "";
});//filter
return filteredNames;
}//splitNames()
console.log( splitNames() );
Create a new array and push what you need.
function splitNames(){
var names = document.getElementById("1").value.split("\n");
var newArr = [];
for(var i = 0; i<=names.length; i++){
if(names[i]){
newArr.push(names[i]);
}
}
return newArr.join('\n');
//console.log(names);
}
try it:
function splitNames(){
var names = document.getElementById("1").value.split("\n");
var newArr = names.filter(function(name){
return name!=="";
});
return newArr;
}

Categories

Resources