How to find the array from the string? [duplicate] - javascript

This question already has answers here:
Regular expression to extract text between square brackets
(15 answers)
Closed 1 year ago.
const str = "[1,2,3,4],5,6";
const getArray = (str) => {
...
return arr;
}
console.log(getArray(str)); //[1,2,3,4]
[1,2,3,4] is the expected array.
How can I get this one?

You can use regex for extracting the numbers enclosed by [] then run a map for sanitize. Check this-
const str = "[1,2,3,4],5,6";
const getArray = str => {
const regex = /(\[([^\]]+)\])/;
const match = regex.exec(str);
return match?.[2] ? match[2].split(',').map(x => x.trim()) : [];
}
console.log(getArray(str));

You can use the JavaScript method lastIndexOf() to find the [ and ].
This will give you all characters in-between [ and ].
Then you can use the split() method to convert the array.
Using map() and Number you can convert string to number
const str = "[1,2,3,4],5,6";
function getArray(str){
var myArray = str.substring(
str.lastIndexOf("[") + 1,
str.lastIndexOf("]")
);
return myArray.split(",").map(Number);
}
console.log(getArray(str));

This will give you an array of all arrays within your string.
const str = "[1,2,3,4],5,6";
const getArray = (str) => {
const ans = []
let stack = []
let isStack = true
for (let i = 0; i < str.length; i++) {
if (str[i] == '[') {
isStack = true;
} else if (str[i] == ']') {
isStack = false;
ans.push(stack)
stack = []
} else if (isStack && str[i] != ',') {
stack.push(parseInt(str[i]))
}
}
return ans;
}
console.log(getArray(str)) // [ [ 1, 2, 3, 4 ] ]
console.log(getArray(str)[0]) // [ 1, 2, 3, 4 ]

Assuming that str contains exactly one pair of enclosing square brackets:
const getArray = (str) => {
const idxStart = str.indexOf('[') + 1
const idxEnd = str.indexOf(']')
arr = str.slice(idxStart, idxEnd)
return arr.split(',')
}

You can use RegEx to match the string enclosed in []
const str = "[1,2,3,4],5,6";
const getArray = (str) => {
arr = str.match('/\[.*\]/')[0]
return arr;
}
console.log(getArray(str));

Related

Need Regular Expression to fetch string data from array with exact match

I want to match and store string in an array using javascript and need regular expression for this. Other solution also appreciated. separated by '_' if only both matches in string those string from array should be retured only, no other match should be accepted. Array and search string both are dynamic. Below is just an example but solution shoud match for any dynamic data.
Example problem given below.
let arr1 = ['ef','cd','ab','cdab','efab','cdef','ab/cd/ef','cd/ef,ab','cd/ab','ab/ef']
test scenarios:
let search = 'ef_ab';
expected output would be ['efab','ab/ef']
let search = 'ab_cd_ef';
expected output would be ['ab/cd/ef','cd/ef,ab']
let search = 'cd';
expected output would be ['cd']
Any help in javascript for problem is appreciated.
I have tried below regex and looping.
Here word1 for given example could be ab or cd or ef and same could be for word2 , word3
let arr1 = ['ef', 'cd', 'ab', 'cdab', 'efab', 'cdef', 'ab/cd/ef', 'cd/ef,ab', 'cd/ab', 'ab/ef']
let regex = /(?=.*word1)(?=.*word2)(?=.*word3)/;
let arr2 = [];
for (i = 0; i < arr1.length; i++) {
if (regex.test(arr1[i]))
arr2.push(arr1[i]);
}
console.log(arr2)
You may use the input to form a series of regex patterns, each of which must match against the input string. An input which matches all regex patterns is a valid match.
var arr1 = ['ef','cd','ab','cdab','efab','cdef','ab/cd/ef','cd/ef,ab','cd/ab','ab/ef'];
var search = 'ab_cd_ef';
var parts = search.split("_");
for (var i=0; i < arr1.length; ++i) {
var counter = 0;
for (var p=0; p < parts.length; ++p) {
var r = new RegExp("\\b" + parts[p] + "\\b");
if (r.test(arr1[i])) {
++counter;
}
}
if (counter == parts.length) {
console.log(arr1[i] + " => MATCH");
}
}
We need to get some permutations going:
// Heap's algorithm https://stackoverflow.com/a/66122464/295783
const excluding = (i) => (xs) => [... xs.slice (0, i), ... xs.slice (i + 1)];
const permutations = (xs) => xs.length == 0 ? [[]] : xs.flatMap ((x, i) => permutations (excluding (i) (xs)).map (p => (x +' '+ p).trim()));
const findSequence = (arr,str) => {
const parts = str.split("_");
const re = new RegExp(`^${permutations(parts) // ^ from start
.map(part => `${part.replace(/ /g,".?")}`) // with a character or not in between
.join('|')}$`); // to end $ of each string
console.log(re); // just to show the resulting regexp
return arr.filter(item => item.match(re));
}
let arr1 = ['ef', 'cd', 'ab', 'cdab', 'efab', 'cdef', 'ab/cd/ef', 'cd/ef,ab', 'cd/ab', 'ab/ef']
console.log(findSequence(arr1,'ef_ab')) // ['efab','ab/ef']
console.log(findSequence(arr1,'ab_cd_ef')) // ['ab/cd/ef','cd/ef,ab']
console.log(findSequence(arr1,'cd')) // ['cd']

Script to group elements where every character is same to each other

For input:
["abc","def","okg","fed","bca"]
expected output should be:
["abc","bca"],["def","fed"],["okg"]
here "abc", "bca" and "def", "fed" contains same character and "okg" there is no element which contains these character
const arr = ["abc", "def", "okg", "fed", "bca"];
let find = (arr) => {
let res = [];
for (let i = 0; i < arr.length; i++) {
for (let j = 1; j < arr.length; j++) {
if (arr[i].search(arr[j])) {
res.push(arr[j]);
}
}
}
return res;
}
console.log(find(arr))
A reduce will do the trick - it seems the shortest code here (apart from the one using lodash)
const arr = ["abc", "def", "okg", "fed", "bca"],
res = Object.values(arr.reduce((acc, ele) => {
const key = ele.split("").sort();
(acc[key] = acc[key] || []).push(ele)
return acc
}, {}))
console.log(res)
.search returns a number indicating the index of where the match was found. Check that the result isn't -1 instead of checking that the result is truthy. But...
.search isn't the right tool here anyway, because it won't find different combinations of the same character. You need a different approach. One way would be to create an object whose keys are the characters found, and the values are the number of occurrences, then use a sorted representation of that object as a key. For example, have both abc and bca turn into something like:
a,1-b,1-c,1
Iterate through the input array, generating a key for each string, and putting the string on an object with that key. At the end, take the object's values.
const strToKey = (str) => {
const grouped = {};
for (const char of str) {
grouped[char] = (grouped[char] || 0) + 1;
}
return Object.entries(grouped)
.sort((a, b) => a[0].localeCompare(b[0]))
.join('-');
};
let find = (arr) => {
const grouped = {};
for (const str of arr) {
const key = strToKey(str);
grouped[key] ??= [];
grouped[key].push(str);
}
return Object.values(grouped);
}
console.log(find(["abc", "def", "okg", "fed", "bca"]));
Another option, when creating the keys, instead of sorting the object afterwards, you could sort the string first:
const strToKey = (str) => {
const grouped = {};
for (const char of [...str].sort()) {
grouped[char] = (grouped[char] || 0) + 1;
}
return Object.entries(grouped).join('-');
};
let find = (arr) => {
const grouped = {};
for (const str of arr) {
const key = strToKey(str);
grouped[key] ??= [];
grouped[key].push(str);
}
return Object.values(grouped);
}
console.log(find(["abc", "def", "okg", "fed", "bca"]));
const input = ["abc","def","okg","fed","bca"]
function getSortedString (str) {
return [...str].sort().join('');
};
function groupBy(input) {
const grouped = [];
while(input.length) {
const nextInput = [];
const first = input[0];
const matched = [first];
for (let i = 1; i < input.length; i++) {
if(getSortedString(first) === getSortedString(input[i])) {
matched.push(input[i])
} else {
nextInput.push(input[i])
}
}
input = nextInput;
grouped.push(matched);
}
console.log(grouped);
}
groupBy(input);
Using Object.values and groupBy (from lodash), you can get a straightforward solution:
You group your array elements by their "sorted" form and then use Object.values to get the output array.
const arr = ["abc", "def", "okg", "fed", "bca"];
const sortString = (str) => str.split("").sort().join("")
const result = Object.values(_.groupBy(arr, sortString));
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

Convert a String to an Array in Javascript without using split() or any built-in methods and with no more than 1 parameter?

Convert a String to an Array in Javascript without using split() or any built-in methods?
input:
str = "Iam a fullstack javascript developer"
output:
arr = [ 'Iam', 'a', 'fullstack', 'javascript', 'developer' ]
confirmation:
console.log(arr[0]) // Iam
var str="Iam a fullstack javascript developer";
var strCharArr;
[...strCharArr]=str;
var arr=strCharArr.reduce((acc, cv)=>{if(cv==" ") acc.push(""); else acc[acc.length-1]+=cv; return acc;},[""]);
console.log(arr);
[...strCharArr]=str splits the string into an array of characters.
reduce starts with an array of one element of empty string ([""]),
and either adds characters, or, in case of a space, adds an empty string element.
Here is the solution
function stringToArray(str) {
let arr = [''];
let j = 0;
for (let i = 0; i < str.length; i++) {
if (str.charAt(i) == " ") {
j++;
arr.push('');
} else {
arr[j] += str.charAt(i);
}
}
return arr;
}
const arr = stringToArray("Iam a fullstack javascript developer")
console.log(arr[0]) // Iam
Recursive approach with using indexOf and slice
str = "Iam a fullstack javascript developer";
const split = (str, arr) => {
const index = str.indexOf(" ");
if (index > -1) {
arr.push(str.slice(0, index));
split(str.slice(index + 1), arr);
} else {
arr.push(str);
}
return "";
};
const chunks = (str) => {
const arr = [];
split(str, arr);
return arr;
};
console.log(chunks(str));

JS How to for palindrome [duplicate]

This question already has answers here:
Palindrome check in Javascript
(45 answers)
Closed 4 years ago.
The question I have been given is this;
create a function that takes an array of words and returns an array containing only the palindromes.
A palindrome is a word that is spelled the same way backwards.
E.g. ['foo', 'racecar', 'pineapple', 'porcupine', 'pineenip'] => ['racecar', 'pineenip']
This is the code that I create;
let arr = []
let str = words.slice(0)
let pal = str.toString().split("").reverse().join("")
console.log(pal);
for (let i = 0; i < words.length; i++) {
for (let k = 0; k < pal.length; k++) {
if (words[i] == pal[k]) {
arr.push(words[i])
}
}
}
return arr
}
This is the test that my code is run against;
describe("findPalindromes", () => {
it("returns [] when passed []", () => {
expect(findPalindromes([])).to.eql([]);
});
it("identifies a palindrom", () => {
expect(findPalindromes(["racecar"])).to.eql(["racecar"]);
});
it("ignores non-palindromes", () => {
expect(findPalindromes(["pineapple", "racecar", "pony"])).to.eql([
"racecar"
]);
});
it("returns [] when passed no palindromes", () => {
expect(findPalindromes(["pineapple", "watermelon", "pony"])).to.eql([]);
});
});
Does anyone have any any suggestion of how to make my code work?
This is the simplest function that returns true or false if the str is a palindrome or not.
I would use this in combination with the filter function to filter on all palindromes. Like this
function checkPalindrom(str) { //function that checks if palindrome or not
return str == str.split('').reverse().join('');
}
const result = words.filter(word => checkPalindrom(word)); //filter function that filters array to only keep palindromes
Without giving spoilers to the answer (this is a common interview question) a clean approach would be as follows:
Define a function isPalindrome(string): boolean
Use the filter property available on the Array prototype to return an array of only palindromes e.g. inputArray.filter(isPalindrome)
Both can be unit tested separately, for example:
You could define an array of inputs and expected outputs for isPalindrome [{ input: "racecar", expectedOutput: true}, {input: "pineapple", expectedOutput: false}, ...] and loop over each test case.
function isPalindrome(word) {
const firstHalf = word.slice(0, Math.ceil(word.length/2));
const secondHalfReversed = word.slice(Math.floor(word.length/2)).split('').reverse().join('');
return firstHalf === secondHalfReversed;
}
function getPalindromesFromArray(arr) {
return arr.filter(isPalindrome);
}
const wordsArr = ['foo', 'racecar', 'pineapple', 'porcupine', 'pineenip'];
console.log(getPalindromesFromArray(wordsArr));
using for loop and filter
let arr = ["foo", "racecar", "pineapple", "porcupine", "pineenip",'pap','aaaa'];
let palindromes = arr.filter(w => {
let len = w.length;
for (let i = 0; i < len / 2; i++) {
if (w[i] == w[len - i - 1]) {
return true;
} else {
return false;
}
}
});
console.log(palindromes)
To solve that first I would create an isPalindrome function like this:
function isPalindrome(word) {
palindromeWord = ''
for(var i = word.length - 1; i >= 0; i--) {
palindromeWord += word.charAt(i)
}
return palindromeWord === word
}
and then I would check for each word inside the array like this:
let arr = ['foo', 'racecar', 'pineapple', 'porcupine', 'pineenip']
let palindromeArr = []
arr.forEach(word => {
if (isPalindrome(word)) {
palindromeArr.push(word)
}
})
console.log(palindromeArr)
What you have is good, however when you did
var pal = str.toString().split("").reverse().join("")
You changed from an array to a string, then you went into the loop with the string, so pal[k] gave a character and not a word.
To change pal back to an array of strings, split it again, use
var pal = str.toString().split("").reverse().join("").split(",");
var words = ['foo', 'racecar', 'pineapple', 'porcupine', 'pineenip'];
var arr = [];
var str = words.slice(0);
var pal = str.toString().split("").reverse().join("").split(",");
console.log(pal);
for (let i = 0; i < words.length; i++) {
for (let k = 0; k < pal.length; k++) {
if (words[i] == pal[k]) {
arr.push(words[i])
}
}
}
console.log(arr);

Remove duplicate in a string - javascript

I have a string in javascript where there are a lot of duplicates. For example I have:
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"
What can I do to delete duplicates and to get for example x="Int32,Double"?
With Set and Array.from this is pretty easy:
Array.from(new Set(x.split(','))).toString()
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"
x = Array.from(new Set(x.split(','))).toString();
document.write(x);
If you have to support current browsers, you can split the array and then filter it
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double";
var arr = x.split(',');
x = arr.filter(function(value, index, self) {
return self.indexOf(value) === index;
}).join(',');
document.body.innerHTML = x;
Use new js syntax remove Dupicate from a string.
String.prototype.removeDuplicate = Function() {
const set = new Set(this.split(','))
return [...set].join(',')
}
x.removeDuplicate()
function myFunction(str) {
var result = "";
var freq = {};
for(i=0;i<str.length;i++){
let char = str[i];
if(freq[char]) {
freq[char]++;
} else {
freq[char] =1
result = result+char;
}
}
return result;
}
That is a more readable and better parameterized solution:
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"
var removeDup = [...new Set(x.split(","))].join(",");
//result "Int32,Double"
Check This out -
removeDuplicates() function takes a string as an argument and then the string split function which is an inbuilt function splits it into an array of single characters. Then the arr2 array which is empty at beginning, a forEach loop checks for every element in the arr2 - if the arr2 has the element it will not push the character in it, otherwise it will push. So the final array returned is with unique elements. Finally we join the array with the join() method to make it a string.
const removeDuplicates = (str) => {
const arr = str.split("");
const arr2 = [];
arr.forEach((el, i) => {
if (!arr2.includes(el)) {
arr2.push(el);
}
});
return arr2.join("").replace(",", "").replace("", " ");
};
console.log(removeDuplicates( "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"));
Its simple just remove duplicates in string using new Set and join them.
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double";
console.log([...new Set(x)].join(""));
function removeDups(s) {
let charArray = s.split("");
for (let i = 0; i < charArray.length; i++) {
for (let j = i + 1; j < charArray.length; j++)
if (charArray[i] == charArray[j]) {
charArray.splice(j, 1);
j--;
}
}
return charArray.join("");
}
console.log(removeDups("Int32,Int32,Int32,InInt32,Int32,Double,Double,Double"));
You can use Set()
const result = Array.from(new Set(x)).join('')
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"
const result = Array.from(new Set(x)).join('')
console.log(result)
you can use the replaceAll function:
let str = "/Courses/"
let newStr = str.replaceAll('/', '')
console.log(newStr) // result -> Courses
function removeDuplicate(x)
{
var a = x.split(',');
var x2 = [];
for (var i in a)
if(x2.indexOf(a[i]) == -1) x2.push(a[i])
return x2.join(',');
}
const str = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double";
const usingSpread = [...str]
const duplicatesRemove = [...new Set(usingSpread)]
const string = duplicatesRemove.join("")
console.log("After removing duplicates: " + string)
STEPS
convert string to character array using spread operator
new Set will implicitly remove duplicate character
convert character array to string using join("") method

Categories

Resources