JavaScript Change elements in line and print them in different lines - javascript

I have this code to find the matching names and change them to others.
But they change every time and in the same line.
var names1 = ["Rui", "Jose", "Carlos", "Miguel"];
var names2 = ["Rui", "Tiago", "Jose", "Carlos", "Rogerio"];
for (var i = 0; i < names1.length; i++) {
for (var j = 0; j < names2.length; j++) {
if (names1[i] == names2[j]) {
names2[j] = "Maria", "Fred";
}
}
}
console.log(names2);
I want to know how to print them in different lines.
Because it shows like this:
MariaFred
Tiago
MariaFred
MariaFred
Rogerio
And I wanted:
maria,
Fred,
Tiago,
Rogerio.
Can you help me?

You could use an array for the excahnge names and an index for inserting a changed name if a matched name is found.
var names1 = ["Rui", "Jose", "Carlos", "Miguel"],
names2 = ["Rui", "Tiago", "Jose", "Carlos", "Rogerio"],
matched = ["Maria", "Fred"],
index = 0,
i, j;
outer: for (j = 0; j < names2.length; j++) {
for (i = 0; i < names1.length; i++) {
if (names1[i] == names2[j]) {
names2[j] = matched[index++];
index %= matched.length;
continue outer;
}
}
}
console.log(names2);
To speed up the check, you could use a hash table and check against it.
var names1 = ["Rui", "Jose", "Carlos", "Miguel"],
names2 = ["Rui", "Tiago", "Jose", "Carlos", "Rogerio"],
matched = ["Maria", "Fred"],
index = 0,
hash = Object.create(null);
names1.forEach(function (a) {
hash[a] = true;
});
names2.forEach(function (a, i, aa) {
if (hash[a]) {
aa[i] = matched[index++];
index %= matched.length;
}
});
console.log(names2);

instead of
console.log(names2)
try this
for (var i = 0; i < names2.length; i++) {
console.log(names2[i]);
}

Try this:
var names1 = ["Rui", "Jose", "Carlos", "Miguel"];
var names2 = ["Rui", "Tiago", "Jose", "Carlos", "Rogerio"];
var matchFound = false;
for (var i = 0; i < names1.length; i++) {
for (var j = 0; j < names2.length; j++) {
if (names1[i] == names2[j] && matchFound === false) {
// when the name matches, print Maria and Fred in 2 different lines
console.log("Maria,");
console.log("Fred,");
matchFound = true;
} else { // if name doesn't match, just print the element from 2nd array
console.log(names2[j]");
}
}
}

IN the following example, I think the random names should be chosen from some source
var names1 = ["Rui", "Jose", "Carlos", "Miguel"];
var names2 = ["Rui", "Tiago", "Jose", "Carlos", "Rogerio"];
var random_names = ['Maria', 'Fred', 'Someother']
var random_names_counter = 0;
for (var i = 0; i < names1.length; i++) {
for (var j = 0; j < names2.length; j++) {
if (names1[i] == names2[j]) {
names2[j] = random_names[random_names_counter++];
}
}
}
console.log(names2);

Related

Reverse whole string while keeping the spaces at the same position

This is the code I have tried. If we input "We are farmers!" it should return "!s rem raferaeW" however the code I have returns "!s remr aferaeW"
function reverseStr(input){
var array1 = [];
var array2 = [];
var nWord;
for (var i = 0; i < input.length; i++) {
array1.push(input[i]);
}
var spaces = [];
for (var i = 0; i < array1.length; i++) {
if(array1[i] == " ") {
spaces.push(i);
}
}
console.log(array1);
console.log(spaces);
array2 = array1.slice().reverse();
var spaces2 = [];
for (var i = 0; i < array1.length; i++) {
if(array2[i] == " ") {
spaces2.push(i);
}
}
console.log(spaces2);
for (var i = spaces2.length - 1; i >=0; i--) {
array2.splice(spaces2[i], 1);
}
console.log(array2);
nWord = array2.join('');
console.log(nWord);
var array3 = [];
for (var i = 0; i < nWord.length; i++) {
array3.push(nWord[i]);
}
console.log(array3);
for (var i = spaces.length - 1; i >=0; i = i - 1) {
array3.splice(spaces[i], 0, " ");
}
console.log(array3);
var anWord = array3.join('');
return anWord;
}
var input = "We are farmers!";
reverseStr(input);
First I pushed each letter of the input into an array at "array1". Then I made an array for the indexes of the spaces of "array1" called "spaces."
Then "array2" is an array of "array1" reversed.
Then "spaces2" is an array of the indexes for "array2" and then I used a for loop to splice out the spaces in array2. Then "nWord" is "array2" combined to form a new word.
Then "array3" is an array for all of nWord's letters and I used a reverse for loop for try to input spaces into "array3" and using the indexes of the "spaces" array. Unfortunately, it is not returning "!s rem raferaeW" and IS returning "!s remr aferaeW".
I am trying to know how I can use the indexes of the "spaces" array to create spaces in "array3" at indexes 2 and 7.
You just need to make following change
//for (var i = spaces.length - 1; i >=0; i = i - 1) {
// array3.splice(spaces[i], 0, " ");
//}
for (var i = 0; i < spaces.length; i = i + 1) {
array3.splice(spaces[i], 0, " ");
}
You are reading spaces array in reverse but as the problem stated spaces should be at same place. Reading it from start to finish fixed the issue.
function reverseStr(input){
var array1 = [];
var array2 = [];
var nWord;
for (var i = 0; i < input.length; i++) {
array1.push(input[i]);
}
var spaces = [];
for (var i = 0; i < array1.length; i++) {
if(array1[i] == " ") {
spaces.push(i);
}
}
console.log(array1);
console.log(spaces);
array2 = array1.slice().reverse();
var spaces2 = [];
for (var i = 0; i < array1.length; i++) {
if(array2[i] == " ") {
spaces2.push(i);
}
}
console.log(spaces2);
for (var i = spaces2.length - 1; i >=0; i--) {
array2.splice(spaces2[i], 1);
}
console.log(array2);
nWord = array2.join('');
console.log(nWord);
var array3 = [];
for (var i = 0; i < nWord.length; i++) {
array3.push(nWord[i]);
}
console.log(array3);
//for (var i = spaces.length - 1; i >=0; i = i - 1) {
// array3.splice(spaces[i], 0, " ");
//}
for (var i = 0; i < spaces.length; i = i + 1) {
array3.splice(spaces[i], 0, " ");
}
console.log(array3);
var anWord = array3.join('');
return anWord;
}
var input = "We are farmers!";
reverseStr(input);
Here is my best crack at it.
const reverseStr = (input) => {
const revArr = input.replaceAll(' ', '').split('').reverse();
for (let i = 0; i < revArr.length; i++) {
if (input[i] === ' ') revArr.splice(i, 0, ' ');
}
return revArr.join('');
}
let words="Today Is A Good Day";
let splitWords=words.split(' ')
console.log(splitWords)
let r=[]
let ulta=splitWords.map((val,ind,arr)=>{
// console.log(val.split('').reverse().join(''))
return r.push(val.split('').reverse().join(''))
})
console.log(r.join(' '))

Can I use this code below to take user input in an array? If not then how can I?

function arrinp() {
var ar1 = [];
for(i=0;i<3;i++){
for(j=0;j<3;j++){
prompt(ar1.push(ar1[i][j]));
}
}
}
arrinp();
Sure, replace
prompt(ar1.push(ar1[i][j]));
with
ar1[i][j] = prompt("Enter value");
Complete code
function arrinp() {
var ar1 = [];
for (i = 0; i < 3; i++) {
ar1[i] = []; //observe this line as well
for (j = 0; j < 3; j++) {
ar1[i][j] = prompt("Enter value");
}
}
return ar1; //return the array
}
console.log(arrinp());
Demo
function arrinp() {
var ar1 = [];
for (i = 0; i < 3; i++) {
ar1[i] = []; //observe this line as well
for (j = 0; j < 3; j++) {
ar1[i][j] = prompt("Enter value");
}
}
return ar1; //return the array
}
console.log(arrinp());

Javascript - count and remove from an object

I have an object with duplicate values and I want to count all those which have the same value and remove them.
var myArray = [{nr: 'bbc',}, {nr: 'bbc'}, {nr: 'bbc'}, {nr: ccc}];
from this array I want to create another array but remove the duplicated values and count them to be like this.
var myArray = [{nr: 'bbc',amount: 3}}, {nr: ccc,amount: 1}];
You could probably use a better format
var count = {};
for(var i = 0; i < myArray.length; ++i) {
if(typeof count[myArray[i].nr] == 'undefined') {
count[myArray[i].nr] = 0;
}
++count[myArray[i].nr];
}
and this wound yield somehing like:
count = {
bcc: 3,
ccc: 1
};
if you still need it with the structure you specified, then:
var newArray = [];
for(var k in count) {
newArray.push({
nr: k,
amount: count[k]
});
}
If you want the same structure, this will work for you
var newArray = [];
for (var i = 0; i < myArray.length; i++) {
var matched = false;
for (var j = 0; j < newArray.length; j++) {
if(myArray[i].nr === newArray[j].nr){
matched = true;
newArray[j].amount++;
break;
}
};
if(!matched)
newArray.push({nr:myArray[i].nr,amount:1});
};
console.log(newArray);

Why does this code work with my array, but not when I typed in an array of strings? JavaScript

This code works when I have my array of arrays of numbers, but not when I typed in an array of arrays of strings; I did change the code to use .length afterward for the strings, but that helps. The error is with the line of "arr[i].reduce(function (onea, twoa) {" being an undefined function in the second version.
Oh, #user1600124, that prompt might be the error, even though I did still type in "[ ["one", "two", "three"], ["one1", "two2", "three3"] ]", it changed that all into a string. You have solved it, I think, but is there a way for user input without prompt. Thanks, #user1600124 for your solution!
var ArrayWidth = function(arr){
var ret = [], i;
for (i = 0; i < arr.length; i++) {
arr[i].reduce(function (onea, twoa) {
return ret[i] = Math.max(onea.length, twoa.length); //added ".length" to stings version
}, 0); //added ",0" to strings version
ret[i] = ret[i].toString().length;
}
return ret;
}
Working full code of array of arrays of numbers:
//Draws Non=Jagged Table with columns be the arrays in the array of arrays and the first being the heading.
var arrays = [
[111111, 22222, 333],
[444444444, 534334, 63],
[73, 83748395, 9343],
[279571, 327894598571490581, 34815, 2]
];
function ArrayHeight (arr) {
var ret = [], i, j;
for(i = 0; i < arr.length; i++){
window["a"+i] = arr[i];
ret[i] = window["a"+i];
for(j = 0; j < ret[i].length; j++)
ret[i][j] = ret[i][j].toString();
}
return ret;
}
var ArrayWidth = function(arr){
var ret = [], i;
for (i = 0; i < arr.length; i++) {
arr[i].reduce(function (onea, twoa) {
return ret[i] = Math.max(onea, twoa);
});
ret[i] = ret[i].toString().length;
}
return ret;
}
function addSpace (){
var ret = ArrayHeight(arrays);
console.log(ret);
var widthOfRet = ArrayWidth(arrays);
console.log(widthOfRet);
var i, j, k;
for(j = 0; j < ret.length; j++){
for(k = 0; k < (ret[j].length); k++){
for(i = ret[j][k].length; i < (widthOfRet[j] + 1); i++){
ret[j][k] = ret[j][k] + " ";
}
}
}
return ret;
}
var drawTable = function(){
var ret = addSpace();
var ArrayWid = ArrayWidth(arrays);
var table = "", retFirst = "", retSecond = "", totaled = 0, i, j;
for (i = 0; i < ArrayWid.length; i++)
totaled = totaled + ArrayWid[i];
for(i = 0; i < ret.length; i++)
retFirst = retFirst + ret[i][0];
for(i = 0; i < (totaled + ret.length); i++)
retSecond = retSecond + "-";
for(j = 0; j < ret.length; j++)
for(i = 0; i < ret[j].length; i++)
window["reti"+i] = "";
for(j = 0; j < ret.length; j++)
for(i = 0; i < ret[j].length; i++)
window["reti"+i] = window["reti"+i] + ret[j][i];
table = retFirst + "\n" + retSecond;
for(i = 1; window["reti"+i] != undefined; i++)
table = table + "\n" + window["reti"+i];
return table;
}
console.log(drawTable());
nonworking with array of arrays of strings:
//Draws Non-Jagged Table with columns be the arrays in the array of arrays and the first being the heading.
var arrays = prompt("To draw a table, type in an array of arrays. Each array is a column and the first is the heading. Cannot be jagged.", "[ [ , ... ], [, ... ], ... ]");
function ArrayHeight (arr) {
var ret = [], i, j;
for(i = 0; i < arr.length; i++){
window["a"+i] = arr[i];
ret[i] = window["a"+i];
for(j = 0; j < ret[i].length; j++)
ret[i][j] = ret[i][j].toString();
}
return ret;
}
var ArrayWidth = function(arr){
var ret = [], i;
for (i = 0; i < arr.length; i++) {
arr[i].reduce(function (onea, twoa) {
return ret[i] = Math.max(onea.length, twoa.length);
}, 0);
ret[i] = ret[i].toString().length;
}
return ret;
}
function addSpace (){
var ret = ArrayHeight(arrays);
console.log(ret);
var widthOfRet = ArrayWidth(arrays);
console.log(widthOfRet);
var i, j, k;
for(j = 0; j < ret.length; j++){
for(k = 0; k < (ret[j].length); k++){
for(i = ret[j][k].length; i < (widthOfRet[j] + 1); i++){
ret[j][k] = ret[j][k] + " ";
}
}
}
return ret;
}
var drawTable = function(){
var ret = addSpace();
var ArrayWid = ArrayWidth(arrays);
var table = "", retFirst = "", retSecond = "", totaled = 0, i, j;
for (i = 0; i < ArrayWid.length; i++)
totaled = totaled + ArrayWid[i];
for(i = 0; i < ret.length; i++)
retFirst = retFirst + ret[i][0];
for(i = 0; i < (totaled + ret.length); i++)
retSecond = retSecond + "-";
for(j = 0; j < ret.length; j++)
for(i = 0; i < ret[j].length; i++)
window["reti"+i] = "";
for(j = 0; j < ret.length; j++)
for(i = 0; i < ret[j].length; i++)
window["reti"+i] = window["reti"+i] + ret[j][i];
table = retFirst + "\n" + retSecond;
for(i = 1; window["reti"+i] != undefined; i++)
table = table + "\n" + window["reti"+i];
return table;
}
console.log(drawTable());
alert("Your table is in the console.log");
my html:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script language="javascript">
//script was here
</script>
</body>
</html>
Thanks! :)
You are calling the reduce function on the content of the input array.
When you have array of arrays of numbers, arr[i] is an array, and hence has the reduce method
When you have array of strings, arr[i] is a string, and do not have the reduce method you tried to use. So you end up with errors
Try this:
function ArrayWidth(ary){
var r = [];
for(var i=0,l=ary.length; i<l; i++) {
r[i] = ary[i].reduce(function(a, b){
return Math.max(a, b);
}, 0);
}
return r;
}

How to merging javascript arrays and order by position?

Is there anyway to merge arrays in javascript by ordering by index/position. I'm try to accomplish this and haven't been able to find any examples of this.
var array1 = [1,2,3,4]
var array2 = [a,b,c,d]
var array3 = [!,#,#,$]
var merged array = [1,a,!,2,b,#,3,c,#,4,d,$]
I know you can use concat() to put one after the other.
As long as the arrays are all the same length you could just do:
var mergedArray = [];
for (var i = 0, il = array1.length; i < il; i++) {
mergedArray.push(array1[i]);
mergedArray.push(array2[i]);
mergedArray.push(array3[i]);
}
EDIT:
For arrays of varying lengths you could do:
var mergedArray = [];
for (var i = 0, il = Math.max(array1.length, array2.length, array3.length);
i < il; i++) {
if (array1[i]) { mergedArray.push(array1[i]); }
if (array2[i]) { mergedArray.push(array2[i]); }
if (array3[i]) { mergedArray.push(array3[i]); }
}
This should work for arrays of ANY length:
var mergeArrays = function () {
var arr = [],
args = arr.slice.call(arguments),
length = 0;
for (var i = 0, len = args.length; i < len; i++) {
length = args[i].length > length ? args[i].length : length;
}
for (i = 0; i < length; i++) {
for (var j = 0; j < len; j++) {
var value = args[j][i];
if (value) {
arr.push(value);
}
}
}
return arr;
};
Example:
var array1 = [1,2,3,4];
var array2 = ['a','b','c','d','e','f','g','h','i','j','k','l'];
var array3 = ['!','#','#','$','%','^','&','*','('];
mergeArrays(array1, array2, array3);
// outputs: [1, "a", "!", 2, "b", "#", 3, "c", "#", 4, "d", "$", "e", "%", "f", "^", "g", "&", "h", "*", "i", "(", "j", "k", "l"]
This would work also (a little more terse syntax):
var mergeArrays = function () {
var arr = [],
args = arr.slice.call(arguments),
length = Math.max.apply(null, args.map(function (a) { return a.length; }));
for (i = 0; i < length; i++) {
for (var j = 0, len = args.length; j < len; j++) {
var value = args[j][i];
if (value) {
arr.push(value);
}
}
}
return arr;
};
For arrays that are all the same size, where you pass one or more arrays as parameters to merge:
function merge()
{
var result = [];
for (var i=0; i<arguments[0].length; i++)
{
for (var j=0; j<arguments.length; j++)
{
result.push(arguments[j][i]);
}
}
return result;
}
var array1 = ['1','2','3','4'];
var array2 = ['a','b','c','d'];
var array3 = ['!','#','#','$'];
var merged = merge(array1, array2, array3);
Nothing built in, but it wouldn't be hard to manage:
var maxLength = Math.max(array1.length, array2.length, array3.length),
output = [];
for (var i = 0; i < maxLength; i++) {
if (array1[i] != undefined) output.push(array1[i]);
if (array2[i] != undefined) output.push(array2[i]);
if (array3[i] != undefined) output.push(array3[i]);
}
try this...
var masterList = new Array();
var array1 = [1,2,3,4];
var array2 = [a,b,c,d];
var array3 = [!,#,#,$];
for(i = 0; i < array1.length; i++) {
masterList.push(array1[i]);
masterList.push(array2[i]);
masterList.push(array3[i]);
}
It looks like you want to "zip" some number of same-length arrays into a single array:
var zip = function() {
var numArrays=arguments.length
, len=arguments[0].length
, arr=[], i, j;
for (i=0; i<len; i++) {
for (j=0; j<numArrays; j++) {
arr.push(arguments[j][i]);
}
}
return arr;
};
zip([1,2], ['a', 'b']); // => [1, 'a', 2, 'b']
zip([1,2,3], ['a','b','c'], ['!','#','#']); // => [1,'a','#',...,3,'c','#']
If the input arrays could be of different length then you've got to figure out how to deal with that case...
Yes, there is some way to do that. Just:
loop through the larger array,
until at the currently processed position both arrays have elements, assign them one-by-one to the new array,
after the shorter array ends, assign only elements from the longer array,
The resulting array will have the elements ordered by the index from the original arrays. From your decision depends, position in which one of these arrays will have higher priority.
This works for any number of array and with arrays of any length.
function myMerge() {
var result = [],
maxLength = 0;
for (var i = 0; i < arguments.length; i++) {
if (arguments[i].length > maxLength) { maxLength = arguments[i].length; }
}
for (var i = 0; i < maxLength; i++) {
for (var j = 0; j < arguments.length; j++) {
if (arguments[j].length > i) {
result.push(arguments[j][i]);
}
}
}
return result;
}
Eli beat me to the punch up there.
var posConcat = function() {
var arrays = Array.prototype.slice.call(arguments, 0),
newArray = [];
while(arrays.some(notEmpty)) {
for(var i = 0; i < arrays.length; i++) {
if(arguments[i].length > 0)
newArray.push(arguments[i].shift());
}
}
return newArray;
},
notEmpty = function() { return arguments[0].length > 0; };
Usage:
var orderedArray = posConcat(array1,array2,array3);
Sample: http://jsfiddle.net/HH9SR/

Categories