How to refer to the array without changing its' contents - javascript

How am I able to write this so that I do not change the order of myApp.myArr2 and only refer to it instead?
I want the 2nd last line to produce 'hello world' and the last line to produce 'world hello'
myApp.myArr2 = ["hello", "world"];
function reverseArray(temp) {
myApp.myNewArr2 = temp.reverse();
};
reverseArray(myApp.myArr2);
console.log(myApp.myArr2); // world hello
console.log(myApp.myNewArr2); // world hello

Try this:
Change the line from:
myApp.myNewArr2 = temp.reverse();
to
myApp.myNewArr2 = temp.slice().reverse();
A JSFiddle link example is here.
Best of luck.

Array.prototype.reverse make reverse array in-place. This is true. If you want to get copy you can do it with following code:
function reverseCopy(array) {
var copy = [];
array.forEach(function(e) { copy.unshift(e); });
return copy;
}

To get a copy of an array you can do:
var newArray = oldArray.slice();

Related

Need to display full array as a string in an innerHTML element

Ok this must have a simple solution but I'm breaking my head over this one...
I have a js code which picks up ID numbers from my HTML by class. It stores all in an array. I checked that the array is not undefined and is not empty. Sofar so good.
Now I need to get this array of ID's to display into an HTML element. The full array should just come out as a comma separated string.
The piece of code which is relevant:
function makelink(){
var idArray = $(".result");
document.getElementById("link").innerHTML = idArray;
}
//The result in HTML = [object Object]
When I do the following it works exactly as I want (except that I can't hardcode the array into the code like this of course)
function makelink(){
var idArray = ["123", "124", "125", "126"];
document.getElementById("link").innerHTML = idArray;
}
//The result in HTML = [123,124,125,126]
I read at least 4 other similar questions on Stackoverflow such as What does [object Object] mean? and Convert javascript array to string and based on that I tried:
document.getElementById("link").innerHTML = idArray.join();
and also:
var idArray = $(".result");
idArray.toString();
but I could not figure out how to make it work for my code. I don't need to alert or console.log. I need my result to be output in the HTML. Please help.
You can try this:
function makelink(){
var idArray = [];
$(".result").each(
function(){
idArray.push($(this).text())
}
);
document.getElementById("link").innerHTML = idArray.join(', ');
}
You are not displaying the array, but the jQuery object of the DOM element. You might need the map function. But this function is not enough by itself, you will still need to get the value of the result object, or the html, but that part is the easiest.
function makelink(){
var idArray = $(".result").map(function(item) {
return item.val();
}).get();
document.getElementById("link").innerHTML = idArray;
}
Do this ::
function makelink() {
var idArray = ["123", "124", "125", "126"];
document.getElementById("link").innerHTML = JSON.stringify(idArray);
}

Split php varibale with JS into array

I have tried everything and I can not split a PHP variable into two parts so I can insert them into two input fields. I have read numerous topics here and I don't see the problem...
This peace of code gives me a result that php variable is inserted into a wanted filed.
Lets say the PHP variable is data1-data2:
document.hiderad.selectstate.onchange = updateText;
function updateText() {
var str = document.hiderad.selectstate;
document.hiderad.opis.value = str.value;
}
Code above inserted data1-data2 into wanted HTML input.
And soon as i try to split it i get undefined warning. I have tried 7 different things to approach this problem so i want even list all the versions I tried. Can someone please help?
document.hiderad.selectstate.onchange = updateText;
function updateText() {
var str = document.hiderad.selectstate;
var array = str.toString().split('-');
a = array[0], b = array[1];
document.hiderad.opis.value = a.value;
document.hiderad.iznos.value = b.value;
}
Code above gives me b undefined if i remove last line i get a undefined.
You shouldn't be using a.value and b.value, that's for getting the value of an input field, not a string. You should use that to get the value of the selectstate input.
Also, always declare local variables unless you have a specific reason to assign global variables.
function updateText() {
var str = document.hiderad.selectstate;
var array = str.value.split('-');
var a = array[0], b = array[1];
document.hiderad.opis.value = a;
document.hiderad.iznos.value = b;
}

JavaScript Split from comma separated to array list with values

What I'm trying to do is from a comma separated text (like this one):
hello,test,ciao
Get a javascript array with a predetermined value.
I know how to split a comma-separated list, but I don't know how to add a value inside them.
Actual code:
HTML
<input onkeyup="test()" type="text" id="origin">
<div id="response">
</div>
JAVASCRIPT:
function getValue(){
var returnV = $("#origin").val();
return returnV
}
function test(){
var origin = getValue();
var array = origin.split(',');
console.log(array)
}
OUTPUT
["hello", "test", "ciao"]
WHAT I'M TRYING TO GET
{
"hello":"predetermined value",
"test":"predetermined value",
"ciao":"predetermined value",
}
I think this question is interesting because this way yo can, for example, create new configurations with a starter value and add custom confirgurations for each of them later. I know that the split part is already replied on stackoverflow, what I'm having trouble with is with adding the default values :), thank you very much in advance.
didn't want to change your code so much. just have a look up to object creation.
function getValue(){
return document.getElementById("origin").value
}
function test(){
var obj = {}
var origin = getValue();
origin.split(", ").forEach(function(e) {
obj[e] = "predeterminated value";}
);
console.log(obj);
}
<input onkeyup="test()" type="text" id="origin">
<div id="response">
</div>
Have you tried iterating over the array? Like this:
function getValue(){
var returnV = $("#origin").val();
return returnV
}
function test(){
var origin = getValue();
var object = {}
var array = origin.split(',');
array.forEach((item) => {
object[item] = "predeterminated value"
}
console.log(object)
}
A couple notes: try to give more meaningful names to your variables; the word is "predetermined",
Store your output to a variable:
var output=["hello", "test", "ciao"]
Then do something like this with it:
var newObject={};
for(var i in output){
var property=output[i];
newObject[property]='predeterminated value';
}
Example JSFiddle (open console to see result)
Split your string and then use Array.prototype.reduce to build an object from it.
var original = "hello,test,ciao";
var obj = original.split(',').reduce(function(p,c) {
p[c] = "predeterminated value";
return p;
}, {});
console.log(obj);
It's not exactly clear where predeterminated value is supposed to come from. If it's the same for all properties of your object, then this will work as-is. If it's not, you'll have to figure out how to select the right value.
Hey you can follow the below code snippet this will help
function getValue(){
var returnV = 'hey,your,input,keys,goes,here';
return returnV;
}
function test(){
var origin = getValue();
var array = origin.split(',');
var finalObj = {};
var defaultVal = 'pre-def';
for(var i=0;i<array.length;i++){
finalObj[array[i]] = defaultVal;
}
console.log("arry",array)
console.log("converted",finalObj)
}
test();

Underscore.js `filter` not working

I have the following code snippet I use to choose which suburbs from a list the user has selected (with irrelevant code omitted):
var allSuburbsList = new Array([{"SuburbID":1,"SuburbAreaID":3,"SuburbName":"Alberante","SuburbActive":true,"Area":null,"Agents":[]},{"SuburbID":4,"SuburbAreaID":3,"SuburbName":"Alberton North","SuburbActive":true,"Area":null,"Agents":[]}]);
var a3burbs = _.filter(allSuburbsList, function(s) { return s.SuburbAreaID === 3; });
// 3 is a test value. All the test suburbs so far fall under area no. 3.
With this filter, a3burbs comes out as an empty array, []. If I cheat and make the filter:
var a3burbs = _.filter(allSuburbsList, function(s) { return true; });
then a3bubrs comes out an exact copy of allSuburbsList, with all suburbs included. What could I be doing wrong? I'm using the same syntax as indicated on the Underscore.js home page.
Btw, would the way I populate allSuburbsList from a viewmodel array property have anything to do with this:
var allSuburbsList = new Array(#Html.Raw(JsonConvert.SerializeObject(Model.AllSuburbs)));
Just for interest, my first attempt was the hideous code below, but it worked:
var a3burbs = [];
#{for (var i = 0; i < Model.AllSuburbs.Length; i++) {
#:if (allSuburbsList[#i].SuburbAreaID === 3) {
#:a3burbs.push(allSuburbsList[#i]);
};
};
You're creating a new array and passing in an array.
Change it to
var allSuburbsList = [{"SuburbID":1,"SuburbAreaID":3,"SuburbName":"Alberante","SuburbActive":true,"Area":null,"Agents":[]},{"SuburbID":4,"SuburbAreaID":3,"SuburbName":"Alberton North","SuburbActive":true,"Area":null,"Agents":[]}];
Using new Array([{}]), you are creating an array inside another array. Just instantiate that without new Array()

get an array to print on two lines but its going on one

I am trying to teach myself html n javascript I dont think I'm doing too badly however I am trying to get an array to print on two lines but its going on one like below.
my javascript looks like this:
var Abc = function(foo, bar) {
this.foo=foo;
this.bar=bar;
}
var def = new Abc("foo", ["foo", "bar"]);
var ghj = new Abc("bar", "foo");
var klm = [def, ghj];
for(var i = 0; i < klm.length; i++) {
var testPara = document.createElement("p");
var testNode = document.createTextNode(klm[i].foo);
testPara.appendChild(testNode);
document.getElementById(foobar).appendChild(testPara);
var testPara1 = document.createElement("p");
var testNode1 = document.createTextNode(klm[i].foo);
testPara.appendChild(testNode);
document.getElementById(foobar).appendChild(testPara1);
}
my html is like this:
<section id="foobar"></section>
what I want it to print out on the page is
foo
foo
bar
bar
foo
but what I am getting is:
foo
foo,bar
bar
foo
I tried putting a nested for loop to split them up but it just printed out the same thing about 20 times before moving on
Also do I have to put the instances of the object into an array to get this to work or is there another simpler way of doing it?
That's because var def = new Abc("foo", ["foo", "bar"]); defines creates an object like this:
def: {
foo: "foo",
bar: ["foo", "bar"]
}
If you want it to print the contents of def.bar on separate lines, then either:
Split the bar part of def to be one string instead of an array; or
Modify your function to understand that bar can be an array of strings.

Categories

Resources