Compare two arrays and remove items with partial match - javascript

I need to compare two arrays for PARTIAL / SUBSTRING matches. If these are found, I want the matching items removed from the originalArray or create a new array with all those items that did not have a partial match,
var originalArray = ['www.google.com/opq', 'www.yelp.com/abc', 'www.yahoo.com/klm', 'www.bing.com/xyz', 'www.google.com/124'];
var itemsToBeRemoved = ['google.com', 'yahoo.com'];
// DESIRED ARRAY: An array with items that did not have a partial match. For example:
var cleanArray = ['www.yelp.com/abc', 'www.bing.com/xyz']
It work when its a FULL / EXACT match.
But it is NOT what I need.
function cleanFullMatch(){
// Your main array
var originalArray = ['www.google.com/rugby', 'www.yelp.com/abc', 'www.yahoo.com/tennis', 'www.bing.com/xyz', 'www.google.com/football'];
Logger.log(originalArray);
// This array contains strings that needs to be removed from main array
var itemsToBeRemoved = ['www.google.com/rugby', 'www.yahoo.com/tennis', 'www.google.com/football'];
var cleanObj = {};
itemsToBeRemoved.forEach( e => cleanObj[e] = true);
itemsToBeRemoved.forEach( e => itemsToBeRemoved[e]= true);
var cleanArray = originalArray.filter(function(val){ return !cleanObj [val] })
Logger.log(cleanArray);
}

You can use JavaScript RegExp to create regular expression and array.filter(function) to remove elements that does not match the regex.
Sample Code:
function cleanFullMatch(){
// Your main array
var originalArray = ['www.google.com/rugby', 'www.yelp.com/abc', 'www.yahoo.com/tennis', 'www.bing.com/xyz', 'www.google.com/football'];
Logger.log(originalArray);
// This array contains strings that needs to be removed from main array
var itemsToBeRemoved = ['google.com', 'yahoo.com', 'google.com'];
// loop through itemsToBeRemove
itemsToBeRemoved.forEach(function(rgx){
// convert each element of itemsToBeRemove to regular expression
var re = new RegExp(rgx);
// filter the array by removing the elements that match the regex
// test() method checks if the string matches the regex
originalArray = originalArray.filter( word => !re.test(word));
});
Logger.log(originalArray);
}
Sample Output:

filter out the elements of the originalArray so that none of the itemsToBeRemoved is present in any of the filtered elements.
There are many ways to check whether a substring is included in another string, as others said, like includes, indexOf and RegExp.
You could then iterate through all of these itemsToBeRemoved in different ways. You could, for example, use some:
function cleanFullMatch(){
var originalArray = ['www.google.com/rugby', 'www.yelp.com/abc', 'www.yahoo.com/tennis', 'www.bing.com/xyz', 'www.google.com/football'];
var itemsToBeRemoved = ['google.com', 'yahoo.com'];
var cleanArray = originalArray.filter(element => !itemsToBeRemoved.some(item => element.includes(item)));
console.log(cleanArray);
}
Or, alternatively, every:
var cleanArray = originalArray.filter(element => itemsToBeRemoved.every(item => !element.includes(item)));
As you can see, the filtering process can be reduced to a single line.

Related

How to check if a string contains one of the elements from an array in Javascript?

I have a string var str = "I like roses"; and an array containing var arr1 = ['roses','daisy','lily','petunia']
I want to check if my string contains one or more than one element of the array arr1.
Expected Output : str contains an element from arr1
How can I do that in javascript?
I know how to check all the elements in an array using .every.
var str = 'I will have a mango and a banana';
var arr = ['mango','banana'];
var isEvery = arr.every(item => str.includes(item));
console.log(isEvery);
Output: true
How can I do it for just one element?
Array.prototype.some has already been proposed by #Ele and will likely best suit your needs.
One can take the funky route and use a regex
const v = ['mango', 'banana']
const check = s => !!s.match(new RegExp(`(${v.join('|')})`))
console.log(check('me mango and banana'))//true
console.log(check('me mango'))//true
console.log(check('me nothing'))//false
Not an elegant solution but this should work. Im sure you can clean it up
const arrayCompare = () =>{
const str = "I like roses";
const arr1 = ['roses','daisy','lily','petunia']
const newArray = str.split(' ');
for(let element of newArray){
if(arr1.includes(element)){
return 'String contains element from arr1'
}
}
return false;
};

Javascript - How to split a string into a nested array?

I know I can use split function to transform a string to an array but how can a string be split twice to produce a nested array?
I expected this would be sufficent but it does not produce the desired output.
var myString = "A,B,C,D|1,2,3,4|w,x,y,z|"
var item = myString.split("|");
var array = [item.split(",")];
Would it be more optimal to use a for each loop?
EXPECTED OUTPUT
var array = [
["A","B","C","D"],
["1","2","3","4"],
["w","x","y","z"],
];
Once you've split on |, use .map to account for the nesting before calling .split again. There's also an empty space after the last |, so to exclude that, filter by Boolean first:
const myString = "A,B,C,D|1,2,3,4|w,x,y,z|";
const arr = myString
.split('|')
.filter(Boolean)
.map(substr => substr.split(','));
console.log(arr);
Or you could use a regular expression to match anything but a |:
const myString = "A,B,C,D|1,2,3,4|w,x,y,z|";
const arr = myString
.match(/[^|]+/g)
.map(substr => substr.split(','));
console.log(arr);
var myString = "A,B,C,D|1,2,3,4|w,x,y,z"
var item = myString.split("|");
var outputArr = item.map(elem => elem.split(","));
console.log(outputArr);

Alphabetically sort array with no duplicates

I'm trying to create a function that takes an array of strings and returns a single string consisting of the individual characters of all the argument strings, in alphabetic order, with no repeats.
var join = ["test"];
var splt = (("sxhdj").split(""))
var sort = splt.sort()
var jn = sort.join("")
join.push(jn)
function removeDuplicates(join) {
let newArr = {};
join.forEach(function(x) { //forEach will call a function once for
if (!newArr[x]) {
newArr[x] = true;
}
});
return Object.keys(newArr);
}
console.log(removeDuplicates(join));
I can not get the current code to work
Check out the comments for the explanation.
Links of interest:
MDN Array.prototype.sort.
MDN Set
var splt = ("sxhdjxxddff").split("")
// You need to use localeCompare to properly
// sort alphabetically in javascript, because
// the sort function actually sorts by UTF-16 codes
// which isn't necessarily always alphabetical
var sort = splt.sort((a, b)=>a.localeCompare(b))
// This is an easy way to remove duplicates
// by converting to set which can't have dupes
// then converting back to array
sort = [...new Set(sort)]
var jn = sort.join("");
console.log(jn);
Something like this :) Hope it helps!
const string = 'aabbccd';
const array = string.split('');
let sanitizedArray = [];
array.forEach(char => {
// Simple conditional to check if the sanitized array already
// contains the character, and pushes the character if the conditional
// returns false
!sanitizedArray.includes(char) && sanitizedArray.push(char)
})
let result = sanitizedArray.join('')
console.log(result);
Try this:
const data = ['ahmed', 'ghoul', 'javscript'];
const result = [...data.join('')]
.filter((ele, i, arr) => arr.lastIndexOf(ele) === i)
.sort()
.join('');
console.log(result)
There are probably better ways to do it, one way is to map it to an object, use the keys of the object for the used letters, and than sorting those keys.
const words = ['foo', 'bar', 'funky'];
const sorted =
Object.keys(
([...words.join('')]) // combine to an array of letters
.reduce((obj, v) => obj[v] = 1 && obj, {}) // loop over and build hash of used letters
).sort() //sort the keys
console.log(sorted.join(''))

How to split a string by dash at specific position JavaScript

I have a dynamically created array as below:
["171281-0-001-1", "171281-0-001-2"]
Basically, I am creating the value based on a very complex function. But that function does not matter here. Basically for example 171281-0-001-1 is made of Account number + id. 171281-0-001 is Account number and 1 is the id.
The number of dashes can be any number but after the last dash it's always id.
How can I differentiate these from my value and assign it into different variables?
Tried:
for (let key in this.your_reference) {
extractedAccountNumber = key.split('-')[0];
extractedId = key.split('-')[1];
}
But since the dashes can be in any number now, the variables have wrong values. Any idea guys? Thanks in advance
You can use map() and split() to take the item from the last array index:
var arr = ["171281-0-001-1", "171281-0-001-2"];
var idList = arr.map(d => {
d = d.split('-');
return d[d.length - 1];
});
console.log(idList);
You could use a regular expression with two groups: one captured group, which matches anything, then match a dash, then another captured group for digits followed by the end of the string:
["171281-0-001-1", "171281-0-001-2"].forEach((str) => {
// first item in the array is the entire match,
// but you only care about the two capture groups, so ignore the first item:
const [,accountNumber, id] = str.match(/(.+)-(\d+)$/);
console.log(accountNumber);
console.log(id);
});
You can use lastIndexOf and substring for that:
var arr = ["171281-0-001-1", "171281-0-001-2"];
var ids = arr.map(d => d.substring(d.lastIndexOf('-') + 1));
console.log(ids);
const arr = ["171281-0-001-1", "171281-0-001-2"];
const accountDetails = arr.map((item) => {
const itemArr = item.split('-');
const accountNumber = itemArr.slice(0, itemArr.length -1).join('-');
const id = itemArr[itemArr.length - 1];
return {id, accountNumber};
});
console.log(accountDetails);

Javascript : How do I call the array index of the string?

Hello I have a problem when you change the string in order to invoke an array in javascript, please help me,
I have had a array:
var fruit=['Apple','Banana','Orange'];
and I have data string from mysql:
example: var string = '0,2';
How to display an array of fruit which corresponds to the var string?
(Thanks for the help)
You have to split() the string to get an array of indexes instead of a string of indexes :
var indexes = '0,2'.split(','); //use the ',' char to split the string
Now, you have to pick fruits values corresponding to each index in the new indexes array create just before.
var res = []; //The new Array to contains new fruits
indexes.forEach(function(index) { //loop over fruit indexes we want
res.push(fruit[index]); //Add the juicy fruit :)
});
And you got the new array (res) with the juicy fruits :)
JSFiddle
EDIT:
Or, a shorter/nicer solution (thanks to Xotic750)
(the second argument of the map function specify the context (this))
var ids = '0,2';
var fruits = ['Apple','Banana','Orange'];
fruits = ids.split(',').map(function(index) {
return this[index];
}, fruits);
I don't know if it will work or not, but this is what I could think of:
var x = [];
for (var i = 0; i>=string.length; i+=2) {
x.push(fruit[string[i]]);
}
But use only even numbers as a comma is also present in the string.
You will need to split the string into an array by using the Split() method:
var myArray = string.split(",");
Then you can loop over the array and use its values as indexes in the fruit array. For example, the first fruit will be:
fruit[myArray[0]];

Categories

Resources