How to print an array verbatim Javascript [duplicate] - javascript

This question already has answers here:
Convert array to JSON
(12 answers)
Closed 4 years ago.
Say I have an array "x", and x shows as [["A", "B", "C"], ["D", "E", "F"]] in the console. How would I convert this to a string verbatim, with all the brackets and quotes?
For example, this should output
"[["A", "B", "C"], ["D", "E", "F"]]"
(if possible, it would also be nice to add backslashes to the special characters, like "\[\[\"A\", \"B\", \"C\"\], \[\"D\", \"E\", \"F\"\]\]")

Try JSON.stringify:
var x = [["A", "B", "C"], ["D", "E", "F"]];
var string = JSON.stringify(x);

To print it like in your console you can use JSON.stringify().
const arr = [["A", "B", "C"], ["D", "E", "F"]];
const str = JSON.stringify(arr); // [["A","B","C"],["D","E","F"]]
If you also want to add a backslash to every bracket and quotation mark you could loop through every character of the string and add a backslash where it's needed.
// ES6 version
let escapedStr = "";
[...str].forEach(c => {
if (c === ']' || c === '[' || c === '"') c = `\\${c}`;
escapedStr += c;
});
console.log(escapedStr) // \[\[\"A\",\"B\",\"C\"\],\[\"D\",\"E\",\"F\"\]\]
If you do not want use ES6 you can do the same with a simple for loop
for (var i = 0, c=''; c = str.charAt(i); i++) {
if (c === ']' || c === '[' || c === '"') c = `\\${c}`;
escapedStr += c;
}
Edit: Using Regex you can solve the problem in one line
const arr = [["A", "B", "C"], ["D", "E", "F"]];
JSON.stringify(arr).replace(/(\[)|(\])|(\")/g, $1 => `\\${$1}`)

Related

Return a string where every character is replaced with its corresponding value in the cipher object

I am having an issue replacing the value from an object with the keys matching the string letters.
Challenge: Create a function secretCipher that takes in an string(sentence) and an object(cipher). Return a string where every character is replaced with its cooresponding value in the cipher. If the character doesn't exist in the cipher, use the original character.
This is what I've written so far. My console.log's are showing what I need them to however my hang up appears to be somewhere when I try to identy the same corresponding keys to the sentence[i]. I have tried numerous methods like .includes, strictly equals etc.
I also have tried to use .replace to replace any sentence[i] with by value variable.
function secretCipher(sentence, cipher){
let result = '';
let cyf = Object.keys(cipher)
// console.log(cyf)
for (let key in cipher){
let value = cipher[key];
// console.log(value)
}
// iterate through sentence, if char in string is stricktly equal to the key
for (let i = 0; i < sentence.length; i++) {
// console.log(sentence[i])
if (sentence[i].includes(cyf)){
sentence[i] = sentence[i].replace(sentence[i], value)
result += sentence[i]
} else {
result += sentence[i]
}
}
return result;
}
//Uncomment the lines below to test your function:
console.log(secretCipher("lqq me on flcebzzk" , { l : "a", q : "d", z: "o"})); //=> "add me on facebook"
console.log(secretCipher("where are you???" , { v : "l", '?' : "!"})) //=> "where are you!!!"
console.log(secretCipher("twmce" , { m : "n", t : "d", w : "a"})); //=> "dance"
You can iterate through the word more efficiently, but this is pretty simple:
function secretCipher(sentence, cipher){
return sentence.split('').map(letter => cipher[letter] ?? letter).join('');
}
//Uncomment the lines below to test your function:
console.log(secretCipher("lqq me on flcebzzk" , { l : "a", q : "d", z: "o"})); //=> "add me on facebook"
console.log(secretCipher("where are you???" , { v : "l", '?' : "!"})) //=> "where are you!!!"
console.log(secretCipher("twmce" , { m : "n", t : "d", w : "a"})); //=> "dance"
If your browser does not know what ?? is, replace it with ||. It should work on all modern browsers according to MDN.
let value = cipher[key]; does nothing because that value isn't referenced anywhere else (its scope ends after the loop iteration ends)
if (sentence[i].includes(cyf)) { doesn't make sense because sentence[i] is a string (character) and cyf is an array of keys. A string will not contain an array. Check if the array contains the character instead.
sentence[i] = sentence[i].replace(sentence[i], value) won't work because strings are immutable. Create a new string instead.
When a match is found, adding the original sentence[i] doesn't make sense - you want to replace with the value on the object, not with the original character.
function secretCipher(sentence, cipher) {
let result = '';
const keys = Object.keys(cipher);
// iterate through sentence, if char in string is stricktly equal to the key
for (let i = 0; i < sentence.length; i++) {
if (keys.includes(sentence[i])) {
result += cipher[sentence[i]];
} else {
result += sentence[i]
}
}
return result;
}
console.log(secretCipher("lqq me on flcebzzk", {
l: "a",
q: "d",
z: "o"
})); //=> "add me on facebook"
console.log(secretCipher("where are you???", {
v: "l",
'?': "!"
})) //=> "where are you!!!"
console.log(secretCipher("twmce", {
m: "n",
t: "d",
w: "a"
})); //=> "dance"
or, more concisely
function secretCipher(sentence, cipher) {
let result = '';
for (const char of sentence) {
result += cipher[char] ?? char;
}
return result;
}
console.log(secretCipher("lqq me on flcebzzk", {
l: "a",
q: "d",
z: "o"
})); //=> "add me on facebook"
console.log(secretCipher("where are you???", {
v: "l",
'?': "!"
})) //=> "where are you!!!"
console.log(secretCipher("twmce", {
m: "n",
t: "d",
w: "a"
})); //=> "dance"

i wanna delete array element but i have a problem

i wanna delete array element but i have a problem.
i ever looking for google, and stackOverFlow's solution but.. i can't understand well.. and
how to treat well in my code.
for example,
let str = (' a b c d C b A ')
// i wanna array like that ( ["a", "b", "c", "d", "c", "b", "a"] )
// so, first i using replace method. (Unfortunately, blocked str.trim method from academy)
// after using replace method,
let blank = str.replace(" ","")
"a b c d C b A "
// and i using split method,
let arr = blank.toLowerCase().split(" ")
// 'toLowerCase()' is need to solve next matter
and like that
["a", "", "b", "c", "d", "c", "b", "a", ""]
problem is begin,
i wanna delete "" element. but,
target an unspecified index, i cant using splice method.
maybe it need to 'for' ,
for(let i = 0 ; i < arr.length; i++) {
if(arr[i]==="") { ...i dont know what to doo.. }
}
Is my direction correct?
And what and how should we do it? i guess i cant using 'splice' method.. because of that..
You should try as code snippet
var array = ["a", "", "b", "c", "d", "c", "b", "a", ""];
var newArr = array.filter(function (el) {
return el != "";
});
console.log(newArr);
let str = (' a b c d C b A ');
let arr = str.toLowerCase().split('').filter(e=>e!=' ');
May be it what you want

Checking values of one array against another in JS

I'm trying to do a check that the first array contains the same values of the second array.
However I'm confused about my code.
First question is: why is my code running my else statement if all letters in the first array are contained in the second? it will run 2 lines of "this is not valid"
Second question is: if my first array contains a duplicate letter it will still pass the check e.g
["a", "b" , "a", "d", "e", "f"]; even though there is two a's in the first it will see the same "a" again. Anyone know a way around this.
Sorry for my long winded questions but I hope it makes sense. Thanks :)
var letters = ["a", "b" , "c", "d", "e", "f"];
var otherLetters = ["a","b", "c" , "d", "e", "f"];
var i = -1;
while(i<=letters.length){
i++;
if(otherLetters.includes(letters[i])){
console.log("This is valid");
}
else
console.log("This is not valid");
}
You didn't close the brackets. And your loop is very confusing, please use foreach. Here is a working example:
const letters = ["a", "b" , "c", "d", "e", "f"];
const otherLetters = ["a","b", "c" , "d", "e", "f"];
letters.forEach(el => {
if (otherLetters.includes(el)) {
console.log(el + 'is valid');
} else {
console.log(el + 'is not valid');
}
});
You are trying to access array elements which are out of bounds. The script runs 8 iterations over an array with 6 elements.
Nothing to worry, cpog90.
Try this solution.
var letters = ["a", "b" , "c", "d", "e", "f"];
var otherLetters = ["a","b", "c" , "d", "e", "f"];
var i = 0;
while(i<letters.length){
if(otherLetters.includes(letters[i])){
console.log("This is valid");
}
else {
console.log("This is not valid "+i);
}
i++;
}
What went wrong in your logic?
If you declare i = -1 and while(i<=letters.length), As 6 is length of letters, 8 iterations will be done as follows.
For first iteration (i = -1), 'while' condition returns true and checks for 'a'
output: This is valid
For second iteration (i = 0), 'while' condition returns true and checks for 'b'
output: This is valid
For third iteration (i = 1), 'while' condition returns true and checks for 'c'
output: This is valid
For fourth iteration (i = 2), 'while' condition returns true and checks for 'd'
output: This is valid
For fifth iteration (i = 3), 'while' condition returns true and checks for 'e'
output: This is valid
For sixth iteration (i = 4), 'while' condition returns true and checks for 'f'
output: This is valid
For seventh iteration (i = 5), 'while' condition returns true and checks for undefined value.
output: This is not valid
For eighth iteration (i = 6), 'while' condition returns true and checks for undefined value.
output: This is not valid
First of all you have set i = -1 which is confusing since array start position is 0.
The reason your loop is running two extra times is because loop started at -1 instead of 0 and next the condition i <= length.
Since [array length = last index + 1] your loop runs extra two times.
Just to make your code work assign var i = 0 and while condition i < letters.length
Simplest solution is using lodash. It has all optimizations out-of-the-box:
var letters = ["a", "b" , "c", "d", "e", "f"];
var otherLetters = ["f", "a","b", "c" , "d", "e"];
const finalLetters = _.sortBy(letters);
const finalOtherLetters = _.sortBy(otherLetters);
if (_.isEqual(finalLetters, finalOtherLetters)) {
console.log('Two arrays are equal.');
} else {
console.log('Two arrays are not equal.');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
Arrays are index based and starts from 0. So, the -1 and the less than letters.length check puts the code into out of bounds.
var letters = ["a", "b" , "c", "d", "e", "f"];
var otherLetters = ["a","b", "c" , "d", "e", "f"];
var i = 0;
while(i<letters.length)
{
if(otherLetters.includes(letters[i]))
{
console.log("This is valid");
}
else
{
console.log("This is not valid");
}
i++;
}
You can use a combination of Array.prototype.every with Array.prototype.includes, along with some extra guard clauses.
const areSequenceEqual = (arr1, arr2) => {
if (!arr1 || !arr2) {
return false;
}
if (arr1.length !== arr2.length) {
return false;
}
return arr1.every(x => arr2.includes(x));
};
const letters = ["a", "b", "c", "d", "e", "f"];
const otherLetters = ["a", "b", "c", "d", "e", "f"];
const someOtherLetters = ["a", "b", "c", "d", "e", "f", "g"];
console.log(areSequenceEqual(letters, otherLetters));
console.log(areSequenceEqual(letters, undefined));
console.log(areSequenceEqual(letters, someOtherLetters));

Function to display every element of array with each other element once

How do I display every element in an Array with each other element once, but not itself?
For example:
var myArray:any = "a b c d"
And then display:
a,b
a,c
a,d
b,a
b,c
b,d
etc.
A for in for works fine.
var myArray = "a b c d".split(' ');
for (let first of myArray) {
for (let second of myArray) {
if (first !== second) {
console.log(`${first},${second}`)
}
}
}
Try
function f (arr) {
arr.forEach(function(e) {
arr.forEach(function(e2) {
if (e === e2) return;
var str = e + "," + e2;
// print str
});
});
}
f("a b c d".split(' '));
You could also use dankogai/js-combinatorics like this:
cmb = Combinatorics.combination(['a','b','c','d'], 2);
while(a = cmb.next()) console.log(a);
// ["a", "b"]
// ["a", "c"]
// ["a", "d"]
// ["b", "c"]
// ["b", "d"]
// ["c", "d"]
"a b c d".split(' ').map((el, idx, arr)=>{
let elIdx = arr.indexOf(el);
let rest = arr.slice(0,elIdx).concat(arr.slice(elIdx+1)).map((l)=> console.log(`${el},${l}`) );
});
for this you can do imbrication of map fonctions, but you do have to work with arrays
here an exemple:
const myArray = ["a", "b", "c", "d", "e", "f", "g"]
// forEach accept one first param x current value
// second param is optional xi index of value
// third param is optional too and it refer the array itself
myArray.forEach( (x, xi, myArr) => {
myArr.forEach( (y, yi) => {
if(xi !== yi) { console.log(`${x}, ${y}`); }
});
});

Removing Element From Array of Arrays with Regex

I'm using regex to test certain elements in an array of arrays. If an inner array doesn't follow the desired format, I'd like to remove it from the main/outer array. The regex I'm using is working correctly. I am not sure why it isn't removing - can anyone advise or offer any edits to resolve this problem?
for (var i = arr.length-1; i>0; i--) {
var a = /^\w+$/;
var b = /^\w+$/;
var c = /^\w+$/;
var first = a.test(arr[i][0]);
var second = b.test(arr[i][1]);
var third = c.test(arr[i][2]);
if ((!first) || (!second) || (!third)){
arr.splice(i,1);
}
When you cast splice method on an array, its length is updated immediately. Thus, in future iterations, you will probably jump over some of its members.
For example:
var arr = ['a','b','c','d','e','f','g']
for(var i = 0; i < arr.length; i++) {
console.log(i, arr)
if(i%2 === 0) {
arr.splice(i, 1) // remove elements with even index
}
}
console.log(arr)
It will output:
0 ["a", "b", "c", "d", "e", "f", "g"]
1 ["b", "c", "d", "e", "f", "g"]
2 ["b", "c", "d", "e", "f", "g"]
3 ["b", "c", "e", "f", "g"]
4 ["b", "c", "e", "f", "g"]
["b", "c", "e", "f"]
My suggestion is, do not modify the array itself if you still have to iterate through it. Use another variable to save it.
var arr = ['a','b','c','d','e','f','g']
var another = []
for(var i = 0; i < arr.length; i++) {
if(i%2) {
another.push(arr[i]) // store elements with odd index
}
}
console.log(another) // ["b", "d", "f"]
Or you could go with Array.prototype.filter, which is much simpler:
arr.filter(function(el, i) {
return i%2 // store elements with odd index
})
It also outputs:
["b", "d", "f"]
Your code seems to work to me. The code in your post was missing a } to close the for statement but that should have caused the script to fail to parse and not even run at all.
I do agree with Leo that it would probably be cleaner to rewrite it using Array.prototype.filter though.
The code in your question would look something like this as a filter:
arr = arr.filter(function (row) {
return /^\w+$/.test(row[0]) && /^\w+$/.test(row[1]) && /^\w+$/.test(row[2]);
});
jsFiddle
I'm assuming it is 3 different regular expressions in your actual code, if they are all identical in your code you can save a little overhead by defining the RegExp literal once:
arr = arr.filter(function (row) {
var rxIsWord = /^\w+$/;
return rxIsWord.test(row[0]) && rxIsWord.test(row[1]) && rxIsWord.test(row[2]);
});

Categories

Resources