jQuery create new Array with doubling old one

266
June 06, 2017, at 03:59 AM

i have problem where i need to make array from input but each input char need to be doubled in array. for example if input is ABC array need to result in AABBCC. so i end up with this code

if (hex.length < 6) {
    hex.splice(hex.indexOf(hex[i]) + 1, 0, hex[i]);
}

if input is ABC it will output AABBCC
if input is AAB it will output AAAABB

but if first and last character is same like ABA it will end up AAABBA. Why is that?

Answer 1

Instead of explicitly iterating using indexOf which only returns the first index, you might want to try array.Map.

var a = "abc"; 
var b = "aba"; 
var c = "foo         
    
Answer 2

This is because indexOf() returns the first occurrence of the specified value. You can use the reduce() method instead:

const double = arr => arr.reduce((acc, next) => [...acc, next, next], []); 
console.log(double(Array.from('ABA')).join(''));

Answer 3

This is a perfect opportunity to use .map():

var hex = 'ABC'; 
 
var doubledHex = Array.from(hex).map(function(i) { 
  return i + i; 
}).join(''); 
 
console.log(hex); 
console.log(doubledHex);

READ ALSO
.appendTo not working

.appendTo not working

I am trying to count how many items there are in a list and then show the result in a divBut no matter what I do the code below crashes my wordpress site

238
Firefox has very big delay on tap until click event gets triggered

Firefox has very big delay on tap until click event gets triggered

I'm seeing a big delay of seconds after I touched a <a> element in Firefox (54) until the click event gets firedOn Mouse Click I don't see any delay

212
Narrow results by typing case sensitivity issue [duplicate]

Narrow results by typing case sensitivity issue [duplicate]

This question already has an answer here:

209
Navigate to id in Content widget from Text widget on Wordpress page

Navigate to id in Content widget from Text widget on Wordpress page

I have a Wordpress page with a text widget containing a select dropdown menu, along with a JQuery function to scroll to an id of a dl element in a separate content widget on the same pageThe dl elements are contained within separate columns on a different...

251