I don't know why the results are different. Javascript [duplicate] - javascript

This question already has answers here:
Is JavaScript a pass-by-reference or pass-by-value language?
(33 answers)
Closed last month.
let arrays = [ [ ' ', ' ', ' ' ], [ ' ', ' ', ' ' ], [ ' ', ' ', ' ' ] ]
console.log(arrays);
for(i = 0; i < arrays.length; i++){
arrays[i][(arrays.length - 1) - i] = '-'
}
console.log(arrays); //[ [ ' ', ' ', '-' ], [ ' ', '-', ' ' ], [ '-', ' ', ' ' ] ]
This is the result I want.
The code below has a different result.
let input = 6;
const diameter = input; //6
const centralValue = Math.ceil(diameter / 2); //3
const reverseArray = (array) => {return array.slice(0).reverse();} //어레이 뒤집어줌
// const makeUpperLeftArrays = function(centralValue){
// }
let createEmptyArray = (number) => {return new Array(number).fill(' ')} //빈 배열 생성
let emptyArray = createEmptyArray(centralValue);
let addEmptyArrays = function(array){
let addedEmptyArrays = [];
for(i = 1; i <= centralValue; i++){
addedEmptyArrays.push(array)
}
return addedEmptyArrays;
}
let addedEmptyArrays = addEmptyArrays(emptyArray);
let arrays = addedEmptyArrays
//[ [ ' ', ' ', ' ' ], [ ' ', ' ', ' ' ], [ ' ', ' ', ' ' ] ]
console.log(arrays);
for(i = 0; i < arrays.length; i++){
arrays[i][(arrays.length - 1) - i] = '-'
}
console.log(arrays);
please help...
I tried debugging, taking it out of function, changing the name, but it didn't work.

Arrays are passed by reference
[...array] will fix your problem
let input = 6;
const diameter = input; //6
const centralValue = Math.ceil(diameter / 2); //3
const reverseArray = (array) => array.slice(0).reverse() //어레이 뒤집어줌
let createEmptyArray = (number) => Array(number).fill(' ') //빈 배열 생성
let emptyArray = createEmptyArray(centralValue);
let addEmptyArrays = function(array){
let addedEmptyArrays = [];
for(i = 1; i <= centralValue; i++){
addedEmptyArrays.push([...array])
}
return addedEmptyArrays;
}
let addedEmptyArrays = addEmptyArrays(emptyArray);
let arrays = addedEmptyArrays
//[ [ ' ', ' ', ' ' ], [ ' ', ' ', ' ' ], [ ' ', ' ', ' ' ] ]
console.log(arrays);
for(i = 0; i < arrays.length; i++){
arrays[i][(arrays.length - 1) - i] = '-'
}
console.log(arrays);

if you look at this line
addedEmptyArrays.push(array)
you are pushing same array reference again and again so any modification you do here
arrays[i][(arrays.length - 1) - i] = '-'
it is reflected in all the instances ( because they are same instances )
fix is to create a new instance every time you are pushing to the array, just replace the line pointed above with
addedEmptyArrays.push(createEmptyArray(centralValue))
this should give expected result and you can refactor your code to create new instances while pushing

Related

How do I output a list of strings instead of [object : object]?

I was not able to output the list of names like Bart, Lisa & Maggie but had a list of [object: object], [object, object] & [object, object] instead.
Here is the code:
let names = null;
function list(names) {
return names.slice(0, names.length - 2).join(', ') + ', ' +
names.slice(names.length - 2, names.length + 1).join(' & ');
}
console.log(list(names));
Assuming that your names array looks like this :
const names = [{name: 'Bart'}, {name: 'Lisa'}, {name: 'Maggie'}]
I think you can do something like that :
const names = [{name: 'Bart'}, {name: 'Lisa'}, {name: 'Maggie'}]
function list(names){
let str = '';
if (names.length !== 0) {
// Get the last name and remove it from the names array
let last = names.pop();
if (names.length !== 0) { // names may be empty if there was only one value in the initial names array
// Then you need to transform your array from [{name: 'Bart'},...]
// to ['Bart', 'Lisa', 'Maggie'] :
str = names.map( (val, i, arr) => {
if (i !== arr[arr.length - 1]) {
return val.name;
}
}).join(', ')
// From here, str is equal to "Bart, Lisa"
// Now we add "& Maggie" to the string
str += ' & ' + last.name;
}
}
return str;
}
console.log(list(names))
// "Bart, Lisa & Maggie"
(Edit) Or here is another way to do it, by keeping your initial code :
const names = [{name: 'Bart'}, {name: 'Lisa'}, {name: 'Maggie'}]
function list(names){
return names.slice(0, names.length - 2).map(value => value.name).join(', ') + ', ' +
names.slice(names.length - 2, names.length + 1).map(value => value.name).join(' & ');
}
console.log(list(names))
// "Bart, Lisa & Maggie"

Compare two arrays diferent length

I have 2 arrays in jade, with different length sizes I just want to validate if the id is the same so that those are selected and the others are not
// jsCategory length 6
var jsCategory = array1
// jsCategory length 3
var jsMy = array2
var html_option = '';
for (var i = 0; i < jsCategory.length; i++) {
for (var z = 0; z < jsMy.length; z++) {
if (jsCategory[i]._id == jsMy[z]._id) {
//Correct
html_option += '<option value=' + jsCategory[i]._id + ' selected>' + jsCategory[i].name + '</option>';
} else {
//Not Select err
console.log(jsCategory[i]);
}
}
}
document.write(html_option);
It's shorter to use filter and reduce
const findById = inWhere => ({ _id }) => !!inWhere.find(t => t._id === _id)
const html_option = array1
.filter(findById(array2))
.reduce((html, ({_id, name}) =>
html += `<option value=${_id} selected>${name}</option>`, ''))

How do I return a new array of all the inputs as strings?

instructions
Write a function called combiningThings. This function should:
create and return a new array of all inputs as strings
each of the new strings should start with "[index] is [data]"
For example:
combiningThings([1, 2, 3]) // returns ["0 is 1", "1 is 2", "2 is 3"]
combiningThings(['My', 1, 'number']) // returns ["0 is My", "1 is 1", "2 is number"]
this is what I have so far but I think I'm making the array into a string rather than making a new array of strings:
var indexToString = function(arrayTwo) {
var combine = "";
for (var i = 0; i < arrayTwo.length; i++) {
combine += arrayTwo.indexOf(i++) + " is " + arrayTwo[i++];
}
return combine;
};
this works with map:
function combiningThings(arr) {
return arr.map((v, index) => index + ' is ' + v);
}
console.log(combiningThings([1, 2, 3]));
console.log(combiningThings(['My', 1, 'number']));
This should work:
function combiningThings(array) {
return array.map((el, index) => {
return index + ' is ' + el;
});
}
combiningThings(['My', 1, 'number']);
// This will give --> [ '0 is My', '1 is 1', '2 is number' ]

Refactor variables in redux functions

I have to refactor my redux functions
In these 3 cases in am renaming the variable in a different way and i do not want this
See the example
case 'INCREMENT_LIKES' :
const index = action.index;
return [
...state.slice(0,index), // before the one we are updating
{...state[index], likes: state[index].likes + 1},
...state.slice(index + 1), // after the one we are updating
]
case 'INCREMENT_COORDINATES' :
const a = action.index;
let string = state[a].d || state[a].d2;
let array = string.split(" ");
let max = array.length;
let last = max - 2;
let i = (state[a].index || 3) + 1;
if ( i === last ) i = 3;
if (array[i] !== 'M' && array[i] !== 'L') array[i] = parseInt(array[i]) + 20;
return [
...state.slice(0,a), // before the one we are updating
{...state[a], d: array.join(' '), index: i, d2: array.join(' '), index: i }, // updating
...state.slice(a + 1), // after the one we are updating
]
case 'INCREMENT_VIEWBOX' :
const count = action.index;
let string2 = state[count].viewBox;
let array2 = string2.split(" ");
let max2 = array2.length;
let i2 = (state[count].index || 2) + 1;
if ( i2 === max2 ) i2 = 2;
array2[i2] = parseInt(array2[i2]) - 20;
return [
...state.slice(0,count), // before the one we are updating
{...state[count], viewBox: array2.join(' '), index: i2},
...state.slice(count + 1), // after the one we are updating
]
default:
return state;
These are the different variable names in the 3 cases
const index = action.index;
const a = action.index;
const count = action.index;
Same for
let string = state[a].d || state[a].d2;
let string2 = state[count].viewBox;
and
let array = string.split(" ");
let array2 = string2.split(" ");
How can i reuse the same variable name for all the 3 cases?
I mean using the same name for the 3 different cases like:
const index - let string - let array
You can add a scope to each case by wrapping them in curly brackets:
case 'INCREMENT_LIKES' : {
const index = action.index;
return [
...state.slice(0,index), // before the one we are updating
{...state[index], likes: state[index].likes + 1},
...state.slice(index + 1), // after the one we are updating
]
}
case 'SOME_OTHER_ACTION_TYPE' : {
console.log(index) // -> undefined
}

javascript - change every three items in a step of 6 iteration

I have an array of items (length could be different). I need to differently change every first three items, then fourth and fifth, then sixth and start again..
For example:
var arr = [1,2,3,4,5,6,7,9,10];
var newArr = arr.map(function (value, index) {
// indexes 1,2,3 value+1
// indexes 4,5 value+2
// index 6 value+3
// indexes 7,8,9 value+1
// indexes 10,11 value+2
// starting over and over...
});
console.log(newArr);
Thanks!
You can use modulus and some conditions to return what you want
var arr = [1,2,3,4,5,6,7,9,10];
var newArr = arr.map(function (value, index) {
var modulo = (index % 6) + 1,
added = 1;
if ( modulo === 4 || modulo === 5 ) added = 2;
if ( modulo === 6 ) added = 3;
return value + added;
});
document.body.innerHTML = '<pre>' + JSON.stringify(newArr, null, 4) + '</pre>';
Golfed, just for fun
var newArr = arr.map(function (v, i) {
return v + ([3,4].indexOf(i%6) != -1 ? 2 : (i%6) === 5 ? 3 : 1);
});
I think you meant indexes instead of values. If this is the case, then this should work:
var arr = [1, 2, 3, 4, 5, 6, 7, 9, 10];
var newArr = arr.map(function(value, index) {
var m = index % 6;
if (m < 3) {
return value + 1;
}
if (m < 5) {
return value + 2;
} else {
return value + 3;
}
});
alert(newArr);
var arr = [1,2,3,4,5,6,7,9,10];
func_123 = function( value, index ){
console.log( 'stuff of first three ' + value + ' ' + index )};
func_45 = function( value, index ){
console.log( 'stuff of four & five ' + value + ' ' + index )};
func_6 = function( value, index ){
console.log( 'stuff of six ' + value + ' ' + index )};
var newArr = arr.map(function (value, index) {
[ func_123, func_123, func_123, func_45, func_45, func_6 ][ index % 6 ]( value, index )});

Categories

Resources