Array that include any substring from another array? - node.js

I have 2 arrays of the following format:
array1 = ['cat', 'man', 'new']
array2 = ['catch', 'jim', 'manners', 'renew', 'newcomer']
I am trying to find an array that contains items of array 2 if any of the strings in array 1 are contained in the string of array 2. In this case the output would be:
['catch', 'manners', 'renew', 'newcomer']
I know that I could to this with a forloop but am curious if there is a simpler 1 line solution for this?
Thanks!

You can use RegExp.test() and Array.join() to create a regular expression using alternation:
const array1 = ['cat', 'man', 'new'];
const array2 = ['catch', 'jim', 'manners', 'renew', 'newcomer'];
const result = array2.filter(v => RegExp(array1.join('|')).test(v));
console.log(result);
Notes:
You have to be careful when the strings include special characters, they will need to be escaped.
From a performance perspective, it's better to build the RegExp once instead of creating it inside the filter() callback.

With filter(), some() and includes() this can be done in one line:
let array1 = ['cat', 'man', 'new'];
let array2 = ['catch', 'jim', 'manners', 'renew', 'newcomer'];
let ans = array2.filter(x => array1.some(a => x.includes(a)));
console.log(ans);

array1 = ['cat', 'man', 'new']
array2 = ['catch', 'jim', 'manners', 'renew', 'newcomer']
const result = array2.filter(word => array1.some(phrase => word.includes(phrase)))
console.log(result)
You can use filter() and some()

Related

Nodejs - return a subset of a list such that they contain values in the other list

So suppose there are two lists
var parsedList = ['a','b','c','d']
var originalList = ['a#','c#','h#']
And I would like to return a subset of originalList which contains values in the parsedList. (e.g. ['a#','c#'] as 'a' and 'c' is in the parsedList) Is there a simple and elegant way to do this?
This approach is very straightforward and elegant, first you loop over your originalList
and then for each element in that array, you want to check if parsedList includes it or not, and you can do that with parseList.includes()
var parsedList = ['a','b','c','d']
var originalList = ['a','c','h']
let newArr = []
originalList.forEach(element => {
if (parsedList.includes(element)){
newArr.push(element)
}
})
console.log(newArr) // ['a', 'c']
do you want something like that or you want to editoriginalList ?
in case you want it in the same array
originalList = originalList.filter(element => {
return parsedList.includes(element)
})
console.log(originalList) // ['a', 'c']

Insert character inside array data

how to insert character from array?
This my data :
["a", "b", "c", ...]
i'm wanna change my data like this:
["$a", "$b", "$c", ...]
Thanks before
let a = ["a", "b", "c", ...]
a.map(value => '$'+value) // this will do what you need returns ["$a", "$b", "$c"]
map basically iterate through the array and map each element according to the given condition
Array.map(value => map the value with any type of data here)
Use map - ES6 way
Map mdn
const arr = ['a', 'b']
const modifiedArray = arr.map(el => '$' + el)
console.log(modifiedArray)
However note it will modify the original array so if you don't want to modify original array
Use spread of ES6
spread mdn
const modifiedArray = {...arr}.map(el => '$' + el)
Non ES6
var arr = ['a', 'b'],
modifiedArr = []
for(let i=0; i < arr.length; i++) {
modifiedArr.push('$' + arr[i])
}
console.log(modifiedArr)

add array of string arrays to array of string [duplicate]

This question already has answers here:
How to merge two arrays in JavaScript and de-duplicate items
(89 answers)
Closed 4 years ago.
I want to add mongo ids in a final array from my query, here is what i am trying to do
var arr = [];
// array1 = [ "59ae3b20a8473d45d11987f8",
"59bb8a9c8f541e060054580e",
"59ae905f43d38f64d85d3c21"]
//array2 = [
"59bce938cbe9c90271742c1a",
"59bcebb4cbe9c90271742c2e" ]
and when i am adding them as arr.push(array1), arr.push(array2)
then i am getting this result
//arr = [ 59ae3b20a8473d45d11987f8,
59bb8a9c8f541e060054580e,
59ae905f43d38f64d85d3c21,
59bce938cbe9c90271742c1a,
59bcebb4cbe9c90271742c2e ]
in result array the type has changed(from strings) and i want these elements as string as they are in array1 and array2, i tried using concat but not working, please help
Using the concat method, you could proceed as:
arr = [].concat(array1, array2)
or even just arr = array1.concat(array2). Here, the result is assigned to arr since concat does not mutate the original array.
Alternatively, using the spread syntax:
arr = [...array1, ...array2]
array1 = [ "59ae3b20a8473d45d11987f8",
"59bb8a9c8f541e060054580e",
"59ae905f43d38f64d85d3c21"]
array2 = [
"59bce938cbe9c90271742c1a",
"59bcebb4cbe9c90271742c2e" ]
var finalArr = array1.concat(array2);
console.log(finalArr);
array1 = [ "59ae3b20a8473d45d11987f8",
"59bb8a9c8f541e060054580e",
"59ae905f43d38f64d85d3c21"]
array2 = [
"59bce938cbe9c90271742c1a",
"59bcebb4cbe9c90271742c2e" ]
var finalArr = [...new Set([...array1 ,...array2])];
console.log(finalArr);

Lodash union of arrays of mongoose ObjectId

I have 2 arrays that containing ObjectId items: array1 array2
I want to create a union between those 2 arrays. for that i'm running:
let res = _.union(array1, array2);
But res contains duplicates ObjectId.
How can i solve this?
If you're looking at two different arrays with strings of 'objectIDs' you can use concat and then uniq to remove the duplicates. Don't forget to run valueOf at the end of your Lodash chain to call it to execute.
Below is an illustrative example:
let array1 = ['42142141221421d', '9999'];
let array2 = ['s421421412412fef3', '42142141221421d', '1234'];
const res = _(array1)
.concat(array2)
.uniq()
.valueOf();
console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
You could try using _.uniqBy(res, 'ObjectId'); That should remove duplicate objectId in your new res array
let newRes = _.uniqBy(res, 'ObjectId');

Most frequent element in a string array, MATLAB

I have a string array, for instance:
arr = ['hello'; 'world'; 'hello'; 'again'; 'I----'; 'said-'; 'hello'; 'again']
How can I extract the most frequent string, which is 'hello' in this example?
First step, use a cell array rather than string array:
arr = {'hello', 'world'; 'hello', 'again'; 'I----', 'said-'; 'hello', 'again'};
Second, use unique to get the unique strings (this doesn't work on a string array, which is why I suggest the cell):
[unique_strings, ~, string_map]=unique(arr);
Then use mode on the string_map variable to find the most common values:
most_common_string=unique_strings(mode(string_map));
It is better to use cell arrays and regexp function; the behavior of string arrays may not be what you expect.
arr = {'hello', 'world'; 'hello', 'again'; 'I----', 'said-'; 'hello', 'again'};
If you use
hellos = sum(~cellfun('isempty', regexp(arr, 'hello')));
it will return the number of 'hello''s in cell array arr.

Resources