JavaScript - Copy item reference of an array - javascript

The answer might be obvious but I didn't find out. I have this code :
const arr = ["Hello"];
let currentStr = arr[0];
currentStr += " world";
console.log(currentStr); // prints "Hello world"
console.log(arr); // prints ["Hello"]
I just want to copy the string reference so when I change the currentStr value, it also change its reference in the array (here the first item of the arr array).
const arr = ["Hello"];
let currentStr = arr[0];
currentStr += " world";
console.log(currentStr); // prints "Hello world"
console.log(arr); // expect print ["Hello world"]

In Javascript strings are immutable. I.e. when you make a change to a string behind the scenes Javascript is making a new copy of that string. Arrays are slightly different. You can mutate arrays. I.e. change what they are storing.
To achieve what you want you can use the splice method on the array to replace the 'Hello' string with a new string called 'Hello' + ' World'. Here is the code for it.
const arr = ['Hello']
arr.splice(0,1, arr[0] + ' World')
console.log(arr) // ['Hello World']
See the MDN docs on Arrays, and the splice method.

const arr = ["Hello"];
var currentStr=[];
let newStr= arr[0]+" World";
currentStr.push(newStr)
console.log(currentStr); //
console.log(arr); //

You can do this by re-assigning currentStr to arr[0].
const arr = ["Hello"];
let currentStr = arr[0];
currentStr += " world";
console.log(currentStr); // prints "Hello world"
arr[0] = currentStr;
console.log(arr); // prints ["Hello world"]

Related

Replace instances of an array in a string with another array

I'm working on a JS applet that requires replacement of array entries in a given string with entires from another array. This is my code as it now stands:
const string = "Lion, Unicorn, Unicorn";
const array1 = ["Lion", "Unicorn"];
const array2 = ["Fox", "Hound"];
const string2 = string.replaceAll(array1[0],array2[0]) //returns "Fox, Unicorn, Unicorn"
My desired output is :
Fox, Hound, Hound.
Specifically, I'd like to turn the contents of string2 into a function that repeats for every item in an array, but have no idea where to start.
Thanks!
Do you mean something like this?
I hope I understood the question well.
You can write a recursive function:
let string = "Lion, Unicorn, Unicorn";
let array1 = ["Lion", "Unicorn"];
let array2 = ["Fox", "Hound"];
function myCustomReplace(str, a1, a2) {
let wordToReplace=a1.shift(); // a1[0] - if array change matters
let replacementWord=a2.shift(); // a2[0] - if array change matters
if (!wordToReplace || !replacementWord) return str;
str=str.replaceAll(wordToReplace, replacementWord );
return myCustomReplace(str,a1,a2); // rturn myCustomReplace(str,a1.slice(1),a2.slice(1)) - if array change matters
}
console.log(
myCustomReplace(string,array1,array2)
)
It's sometimes worthwhile to first transform the inputs into a shape that is easier to work on. For this problem, the input sentence is better thought of as an array of words, and the two arrays used for replacement are better represented as a single object mapping input words to output words...
let string = "Lion, Unicorn, Unicorn";
let array1 = ["Lion", "Unicorn"];
let array2 = ["Fox", "Hound"];
// transform the inputs
let input = string.split(", ");
let translator = array1.reduce((acc, key, i) => {
acc[key] = array2[i];
return acc;
}, {});
// now input is ['Lion', 'Unicorn', ...]
// and transator is { 'Lion' : 'Fox', ... }
// now the problem is just a two-liner, mapping the input over the translator
let output = input.map(e => translator[e] || e)
console.log(output.join(", "))
If we use split(', ') to convert the string to an array of single words, we can use map() to replace them by searching for a pair with indexOf():
Please see comments in the code. A one-liner can be found at the end.
const string = "Lion, Unicorn, Unicorn";
const array1 = ["Lion", "Unicorn"];
const array2 = ["Fox", "Hound"];
// Split on ', '
let splitted = string.split(', ');
// Map
let result = splitted.map(w => {
// Get position in array1
const i = array1.indexOf(w);
// If we've found something
if (i !== -1) {
// Return replacement
return array2[i];
} else {
// Return original
return w;
}
});
// Create string
result = result.join(', ');
// Show
console.log(result);
// Or, as a one-liner
let result2 = string.split(', ').map(w => (array1.indexOf(w) !== -1) ? array2[array1.indexOf(w)] : w).join(', ');
console.log(result2);

Scan for duplicate values in a string and remove them

I am attempting to scan through and remove any duplicates from a string.
Here is an example scenario:
var str = "Z80.8, Z70.0, Z80.8";
The goal is to pass str into a function and have it returned as "Z80.8, Z70.0"
The string is separated by commas.
Use something like:
str
.split(',')
.map(function(s) { return s.trim() })
.filter(function(v, i, a) { return a.indexOf(v) === i })
.join(', ');
Split will make it an array by splitting the string at every comma.
Map will remove leading and trailing spaces.
Filter will remove any element that is already in the array.
Join will join back the array to one string.
Use regex to get each value and then use Set to remove duplicates.
const data = "Z80.8, Z70.0, Z80.8";
const res = [...new Set(data.match(/\w+\.[0-9]/g))];
console.log(res);
Javascript code splits the string on ", " then defines an anonymous function passed to filter, that takes three parameters representing the item, index and allitems. The anonymous function returns true if the index of this item is the same as the first index of that item found, otherwise false. Then join the elements of the Arrray on comma.
var str = "Z80.8, Z70.0, Z80.8";
var res = str.split(", ").filter(function(item,index,allItems){
return index == allItems.indexOf(item);
}).join(', ');
console.log(res);
Result:
Z80.8, Z70.0
Try this:
let str = "Z80.8, Z70.0, Z80.8";
str = [...new Set(str.split(", "))].join(", ");
console.log(str);
let str = "Z80.8, Z70.0, Z80.8";
let uniq = [...new Set(str.split(", "))].join(", ");
You can convert string to array using split() and then convert it to Set and then again join() it
var str = "Z80.8, Z70.0, Z80.8";
str = [... new Set(str.split(', '))].join(', ')
console.log(str);
I suggest to split this into an array then remove duplicates.
var arr = str.replace(" ", "").split(",");
var uniqueArray = arr.filter((v, i, arr) => arr.indexOf(v) === i);

search on string with array with javascript

search on string with array with javascript
i have a string, i need to search on it with array.
for ex.
// that is array what i have
var arr = ['egypt', 'london', 'spain'];
// that is strings what i have
var str = "hello from egypt";
var str2 = "hello from london and spain";
ex. for first string, i need to now if it contain any values from array, and get it.
like : // found one value 'egypt' on str.
like : // found two values 'london, spain' on str2.
You can use includes to see if array elements exist in the string or not
Here's the code that resolves your problem
// that is array what i have
var arr = ['egypt', 'london', 'spain'];
// that is strings what i have
var str1 = "hello from egypt";
var str2 = "hello from london and spain";
function searchWords(str){
var res="";
for(var i=0;i<arr.length;i++){
if (str.includes(arr[i])){
res+= arr[i] +' '
}
}
console.log('found one value '+res )
}
searchWords(str1);
searchWords(str2);
// that is array what i have
var arr = ['egypt', 'london', 'spain'];
// that is strings what i have
var str = "hello from egypt";
var str2 = "hello from london and spain";
function search_in_string(_string, _array){
var out_arr=[];
for(var key in _array){
if(_string.indexOf(_array[key]) !=-1){
out_arr.push(_array[key]);
}
}
return out_arr;
}
console.log(search_in_string(str, arr));
console.log(search_in_string(str2, arr));

Regex for creating an array from String

I have a string as follows
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
I want to get three arrays from above string as follows
var arr1 = ["series-3","series-5","series-6"];
var arr2 = ["a3","a4","a5"];
var arr3 = ["class a", "class b"];
What regex should I use to achieve this?
Can this be done without regex?
Use String#split() method
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
// split string based on comma followed by [
var temp = str.split(/,(?=\[)/);
// remove [ and ] from string usning slice
// then split using , to get the result array
var arr1 = temp[0].slice(1, -1).split(',');
var arr2 = temp[1].slice(1, -1).split(',');
var arr3 = temp[2].slice(1, -1).split(',');
console.log(arr1, arr2, arr3);
Or same method with some variation
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
// Remove [ at start and ] at end using slice
// and then split string based on `],[`
var temp = str.slice(1, -1).split('],[');
// then split using , to get the result array
var arr1 = temp[0].split(',');
var arr2 = temp[1].split(',');
var arr3 = temp[2].split(',');
console.log(arr1, arr2, arr3);
RegEx and String methods can be used. It's better to create an object and store individual arrays inside that object.
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
// Match anything that is inside the `[` and `]`
var stringsArr = str.match(/\[[^[\]]*\]/g);
// Result object
var result = {};
// Iterate over strings inside `[` and `]` and split by the `,`
stringsArr.forEach(function(str, i) {
result['array' + (i + 1)] = str.substr(1, str.length - 2).split(',');
});
console.log(result);
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
var stringsArr = str.match(/\[[^[\]]*\]/g);
var result = {};
stringsArr.forEach(function(str, i) {
result['array' + (i + 1)] = str.substr(1, str.length - 2).split(',');
});
console.log(result);
To create the global variables(Not recommended), just remove var result = {}; and replace result by window in the forEach.
I would prefer to do it like this
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]",
arrs = str.match(/[^[]+(?=])/g).map(s => s.split(","));
console.log(arrs);
Just for the fun of it, another way where we add the missing quotes and use JSON.parse to convert it to a multidimensional array.
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
var result = JSON.parse("[" + str.replace(/\[/g,'["').replace(/\]/g,'"]').replace(/([^\]]),/g,'$1","') + "]");
console.log(result[0]);
console.log(result[1]);
console.log(result[2]);

Get length of every element in array - JavaScript

I want to get length of every element in array
my code is
var a = "Hello world" ;
var chars = a.split(' ');
so I will have an array of
chars = ['Hello' , 'world'] ;
but how I can get length of each word like this ?
Hello = 5
world = 5
You can use map Array function:
var lengths = chars.map(function(word){
return word.length
})
ES6 is now widely available (2019-10-03) so for completeness — you can use the arrow operator with .map()
var words = [ "Hello", "World", "I", "am", "here" ];
words.map(w => w.length);
> Array [ 5, 5, 1, 2, 4 ]
or, very succinctly
"Hello World I am here".split(' ').map(w => w.length)
> Array [ 5, 5, 1, 2, 4 ]
The key here is to use .length property of a string:
for (var i=0;i<chars.length;i++){
console.log(chars[i].length);
}
You could create a results object (so you have the key, "hello", and the length, 5):
function getLengthOfWords(str) {
var results = {};
var chars = str.split(' ');
chars.forEach(function(item) {
results[item] = item.length;
});
return results;
}
getLengthOfWords("Hello world"); // {'hello': 5, 'world': 5}
Try map()
var words = ['Hello', 'world'];
var lengths = words.map(function(word) {
return word + ' = ' + word.length;
});
console.log(lengths);
You can use forEach, if you want to keep the words, and the length you can do it like this:
var a = "Hello world" ;
var chars = a.split(' ');
var words = [];
chars.forEach(function(str) {
words.push([str, str.length]);
});
You can then access both the size and the word in the array.
Optionally you could have a little POJO object, for easier access:
var a = "Hello world" ;
var chars = a.split(' ');
var words = [];
chars.forEach(function(str) {
words.push({word: str, length: str.length});
});
Then you can access them like:
console.log(words[0].length); //5
console.log(words[0].word); //"Hello"
Or using map to get the same POJO:
var words = chars.map(function(str) {
return {word: str, length: str.length};
});

Categories