join array elements with specified element to be placed at the end - javascript

I have an array
input = ["Hi","Bye","Hello","Jose","Juan",null,"How","","Disco"]
I want to always place the word "Bye" to the end of the joined string
I have tried with
input.filter(Boolean).join("#"))
expected output
"Hi#Hello#Jose#Juan#How#Disco#Bye"
I am looking for the best efficient way, or if there is a way to add a filter function along with Boolean filter

Use a filter function that compares with Bye after performing the boolean test.
Then append #Bye to the end of the result.
input = ["Hi", "Bye", "Hello", "Jose", "Juan", null, "How", "", "Disco"];
console.log(input.filter(s => s && s != 'Bye').join("#") + '#Bye');

1) Filter input array that are not empty, null and along with filter you can count of Bye(There can be multiple Bye)
2) Create a new array that only contains Bye using Array.from and append it after the filtered array.
3) Then, at last, you can join array.
const input = ["Hi", "Bye", "Hello", "Jose", "Juan", null, "How", "", "Disco"];
let length = 0;
const result = input
.filter((s) => {
if (s === "Bye") ++length;
return s && s !== "Bye";
})
.concat(Array.from({ length }, () => "Bye"))
.join("#");
console.log(result);

Sort the Byes to the end?
const input = ['Hi', 'Bye', 'Hello', 'Jose', 'Juan', null, 'How', '', 'Disco'];
const output = input
.filter(Boolean)
.sort((a, b) => (a === 'Bye') - (b === 'Bye'))
.join('#');
console.log(output);

If it is a string then one way to get the result is to
const outputString=input.filter(Boolean).join("#"))+"#bye"

Related

Fill empty values of a nested array with specific value Javascript

I have a function called Action which receives an array parameter like this.
[
['X','','O'],
['O','','O'],
['X','X','']
]
I want this function to return an array like this where each empty section of the previous array is filled individually with a specific value, e.g Y.
[
[
['','Y',''],
['','',''],
['','','']
],
[
['','',''],
['','Y',''],
['','','']
],
[
['','',''],
['','',''],
['','','Y']
]
]
I know I can do that with forEach but it needs nested forEach which I think isn't very optimal. Is there any better way of doing that?
This should work:
let arr = [
['X','','O'],
['O','','O'],
['X','X','']
]
let res = []
arr.map((item, index)=>{
item.map((sub, indx) =>{
if(sub === ""){
let array_=
[
['','',''],
['','',''],
['','','']
];
array_[index][indx] = "Y";
res.push(array_)
}
})
})
console.log(res)
You could avoid nesting loops with the following steps
flatten the matrix into a 1-d array
get the indices of the empty sections
create new flatten 1-d arrays with empty indices from previous result marked as 'Y'
transform flatten 1-d arrays back to 3x3 matrix
const arr = [
["X", "", "O"],
["O", "", "O"],
["X", "X", ""],
]
const res = arr
.flat() // flatten the array
.map((section, i) => [section, i])
.filter(([section, _]) => section === "")
.map(([_, i]) => i) // get the indices of empty sections
.map(sectionIdx =>
Array.from({ length: 9 }, (_, i) => (i === sectionIdx ? "Y" : ""))
) // create new flattened array with empty indices marked as 'Y'
.map(flattenedArr => [
flattenedArr.slice(0, 3),
flattenedArr.slice(3, 6),
flattenedArr.slice(6, 9),
]) // turn back flatten array into 3x3 matrix
console.log(res)
I feel compelled to give the trivial answer, which is to continue using nested .forEach. This results in very readable code, which is, in my experience, more valuable than high performance code most of the time.
I'd begin by looping over each row and column of your input. Every time you encounter an matching cell (i.e. empty string, in your case), clone the input structure (using .map to '') and replace the matching element with the desired replacement string (e.g. 'Y').
const input = [
['X','','O'],
['O','','O'],
['X','X','']
]
const result = [];
input.forEach((row, iRow) => row.forEach((col, iCol) => {
if (col == '') {
const clone = input.map(row => row.map(col => ''));
clone[iRow][iCol] = 'Y';
result.push(clone);
}
}));
console.log(result);

How can I check if a string item within an array is all uppercase?

I have an array called Symbols, it gets strings found by a regular expression pushed into it.
I now need to sort through the array and find out if there is a string that has every letter capitalized in it. I have tried similar things in the classified function below everything has returned "false" thus far, even if there is an element that is just "AAAA"
let symbols = [];
let regr = RegExp(/{\$([^\$]+)\$}/, 'g')
function genToken(inStream){
let array;
let vrtStream = inStream.trim();
console.log("Extracting meaningful symbols from string: ", vrtStream);
while((array = regr.exec(vrtStream)) !== null){
console.log(`Meaningful symbol: ${array[0]} found and assigned. Next starts at ${regr.lastIndex}.`)
symbols.push(array)
}
if(symbols.length > 0){
for(index = 0; index < symbols.length; index++){
symbols[index].splice(0, 1);
console.log(`${symbols[index].length} meaningful symbols currently indexed.`);
console.log(symbols);
}// end for
return classify(symbols);
} else {
console.log("no elements in array");
}
function classify(data, index){
console.log("Classify called", symbols)
//symbols is data
symbols.forEach(function(item, index, array){
if(item.toUpperCase == true){
console.log(`${item} is upper`)
} else {
console.log('false');
}
})
}
}
If you need to know which items in an array are all caps, you can map over them and use the regexp test method:
const arr = ['aaa', 'aAa', 'AAa', 'AAA', 'AAAa'];
const allCaps = arr.map(el => /^[A-Z]+$/.test(el));
console.log(allCaps);
If you just need to find the first one, or filter to only include the ones that match, you can use the find or filter array methods:
const arr = ['aaa', 'aAa', 'AAa', 'AAA', 'AAAa', 'BBBB'];
const first = arr.find(el => /^[A-Z]+$/.test(el));
console.log(first);
const all = arr.filter(el => /^[A-Z]+$/.test(el));
console.log(all);
Easy way to check if string is all uppercase is create uppercase string from it and then check if it is same as old string
// just some dummy data
const array = ["some data", "AAAA", "AAaA", "AAAAAB", "ALL_CAPS"];
// actual code to check if string is all uppercase
const allCapsArray = array.filter((str) => str.toUpperCase() === str);
// just printing output
console.log(allCapsArray);

Is there a one-liner to convert '1234567' into ['1234', '567', '', '']?

I need to convert a string into an array with 4 elements, each element has maximum of 4 characters.
"1234567812345678" -> ["1234", "5678", "1234", "5678"]
"12345678123" -> ["1234", "5678", "123", ""]
"" -> ["", "", "", ""]
The reason I want it to be a one-liner is that I need to put it into vue template string so it needs to be an expression other than a series of statements.
I don't want to create a dedicated function to just convert a single parameter to another form.
I managed to split the string into an array but I don't know how to fill in empty slots with '', here's a simplified snippet:
const creditcard = '12345678123';
// need a one liner
const groups = creditcard.split(/(?<=^(?:.{4})+)/);
console.log(groups);
You could pad the string to minimum 16 characters with spaces, then trim the results
const creditcard = '12345678123';
// need a one liner
const groups = creditcard.padEnd(16, ' ').split(/(?<=^(?:.{4})+)/).map(v => v.trim());
console.log(groups);
Another option is to allocate an array with four elements and populate it with splices from your input:
const input = '111122223333444';
const output = Array(4).fill().map((_, i) => input.split('').splice(i*4, 4).join(''));
console.log(output);
// ["1111", "2222", "3333", "444"]
Use slice you can achieve your goal
Here is the code:
function splitToArray(n) {
const ret = [];
for(let i = 0; i < 16; i += 4) {
ret.push(n.slice(i, i + 4))
}
return ret;
}
console.log(splitToArray(''));
console.log(splitToArray('1234567812345678'));
console.log(splitToArray('12345678123'));

How to check the values of an array full of Jquery objects

I am making a tic-tac-toe game for fun and I am trying to do something a little different.
I am currently trying to check winning combinations by iterating through an array of stored tds that were grabbed with Jquery.
WIN_COMBINATIONS = [$("#square_0, #square_1, #square_2"),
$("#square_6, #square_7, #square_8"),
$("#square_0, #square_3, #square_6"),
$("#square_3, #square_4, #square_5"),
$("#square_1, #square_4, #square_7"),
$("#square_2, #square_5, #square_8"),
$("#square_0, #square_4, #square_8"), $("#square_6, #square_4, #square_2")]
So, basically, WIN_COMBINATIONS[0] is a winning combo. What is the best way to iterate through, and actually check the .html of the Jquery object?
Basically, I would like to do something like this
if (WIN_COMBINATIONS[0].html = "X", "X", "X") {
//do something here
}
Thanks for your help!
WIN_COMBINATIONS.forEach(function(combination){
if(combination.map(function(){return $(this).text()}).toArray().join("") == "XXX") {
console.log("winning combination")
}
})
if ES6 (ES2015) is OK than you can try reduce to find match
!!array.reduce(function(a, b){ return (a === b) ? a : NaN; });
Results:
var array = ["a", "a", "a"] => result: "true"
var array = ["a", "b", "a"] => result: "false"
var array = ["false", ""] => result: "false"
var array = ["false", false] => result: "false"
var array = ["false", "false"] => result: "true"
var array = [NaN, NaN] => result: "false"
Warning:
var array = [] => result: TypeError thrown
All credit to:
Lightness Races in Orbit

How to retrieve the value from an array without index

[["Django UnChainers","AA-24010"],["General","AA-26191"]]
I have one array in above form. I want to retrieve all the value with prefix AA (which are in the second position). Is there any way where I can fetch the value by passing prefix?.
I know the way where I can get the value by passing index but may be tomorrow index can get change so is it possible to fetch the value by passing prefix?
In case OP wants a function to do this.
function(arr, pattern){
return arr.map(function(x){
return x.filter( word => ~ word.indexOf(pattern))
});
}
var arr =
[ [ "Django UnChainers", "AA-24010" ], [ "General", "AA-26191" ]];
var list = arr.map(function(x){
if(~(x[1].indexOf('AA'))){
return x[1];
}
});
console.log(list);
In case the index changes in future, iterate through each string and check for the "AA" string. Check the below code.
var arr =
[ [ "Django UnChainers", "AA-24010" ], [ "General", "AA-26191" ]];
var list = arr.map(function(x){
return x.filter( word => ~ word.indexOf('AA'))
});
console.log(list);
this is shorter
var = [nested array]
a.filter(x => x[1].startsWith('AA'))
//in case you are not sure about the index
a.filter(x => x.filter(y => y.startsWith('AA').length > 0))

Categories

Resources