In life, every profession, job, trade, knowledge, etc., requires understanding and knowledge of their foundations, to master and perfect their creation, use and maintenance; to thereby become capable of creating ever more complex and reliable things. In this way, programming 💻 is not the exception and, probably, that statement is, rather, the starting point and the most crucial of this journey.
Speaking more specifically and, regardless of the language of your taste, in Javascript, some of its fundamentals, probably, are algorithms, loops, conditionals, etc. Given this small introduction, I will go to the point and leave here some ways to solve certain operations or situations (these can be random, specific or circumstantial) in particular...
I'll add more different examples and ways to cover most situations, as I can ✋
📣 Feel free to correct me if you find any errors or just want to share your feedback. I would appreciate 👍
These examples use the syntax of
EcmaScript 6
and newer versions
Suppose a situation where you need to split a string "S" and the result must be the same string segmented into "N" number of segments which contain "M" number of characters given a variable "V" ( string => S / V = (N * V:(M * V))
):
var myString = "aaabbbcccdddeeefffggghhhiiijj";
var myNumber = 3;
let length = myString.length, array = [];
var halfLength = (length / myNumber);
for ( let i = 0; i < length; i++ ) {
arr.push( myString.charAt( i );
}
for ( let i = 0; i < halfLength; i++ ) {
const t = ( myNumber * i );
result = arr.slice( t, ( myNumber + t ) ).join( '' );
array.push( result );
}
console.log( `"${ array.join( ' ' ).trim() }"` );
Let's suppose that a situation arises, in which the code you are working on contains an array of values of type number (or integers) and among these, there are some that are repeated and the order is random. What you need from the previous situation is to know what number is the most frequent and what is its frequency?
function mostFrequent ( arr, n ) {
arr.sort();
let max_count = 1, result = arr[ 0 ];
let count = 1;
for ( let i = 0; i < n; i++ ) {
if ( arr[ i ] == arr[ i - 1 ] )
count++;
else
count = 1;
if ( count > max_count ) {
max_count = count;
result = arr[ i - 1 ];
}
}
return result;
}
var arr = [ 1, 2, 2, 2, 5, 4, 6, 3, 2, 2, 4, 5, 6, 7, 8, 8, 8 ];
var n = arr.length;
var count = 0;
var freq = mostFrequent( arr, n );
for ( var i = 0; i < n; i++ ) {
if ( arr[ i ] === freq )
count++;
}
console.log( `
Number: ${ mostFrequent( arr, n ) }` +
`Frequency: ${ count }`
);
In conclusion, this are only some ways to solve these problems; there are many other ways to do it, so use the method that is best for you and don't complicate yourself, just enjoy what you do. 😄