Javascript array - how to print strings only - javascript

I'm a learning newbie.
In my code at:
"https://codepen.io/JonasJsk/pen/qrzLzv"
MYAPPLICATION.DisplayNames = function ()
{
var i, len, str;
for(i = 0, len = MYAPPLICATION.Names.length, str = ""; i < len; ++i)
{
str += MYAPPLICATION.Names[i] + "<br>";
}
console.log(document.getElementById("content").innerHTML = str);
}
I have declared an javascript array with both strings and numbers.
1 - I'm trying to figure out how I can specifically only print-out the strings to the console.
I have been at this for hours, please help me!

Using your code example you can iterate over MYAPPLICATION.Names array with the method Array.prototype.forEach() and validate the typeof every element in the array is an string:
var MYAPPLICATION = MYAPPLICATION || {};
MYAPPLICATION.Names = ["Superman", "Batman", "Flash", 66, 23, 97]
MYAPPLICATION.DisplayNames = function () {
var content = document.getElementById('content');
var ul = document.createElement('ul');
MYAPPLICATION.Names.forEach(function (item) {
if (typeof item === 'string') {
var li = document.createElement('li');
li.appendChild(document.createTextNode(item));
ul.appendChild(li);
}
});
content.innerHTML = '';
content.appendChild(ul);
}
<h2>Lab #2.1</h2>
<button type="button" onclick="MYAPPLICATION.DisplayNames()">
Get Names
</button>
<div id="content"></div>

You can use the typeof operator like this :
var aList = [1, 2, 3, "one", "two", "three"];
for(var i = 0; i < aList.length; i++) {
if(typeof(aList[i]) == "string")
console.log("This is a string : "+aList[i]);
}
I hope this helps. :)

I don't understand your question... Do you want to remove the numbers from the array or you want to print the information only on the console.log ?
Anyway, try this one:
var MYAPPLICATION = MYAPPLICATION || {};
MYAPPLICATION.Names = ["Superman", "Batman", "Flash", 66, 23, 97]
MYAPPLICATION.DisplayNames = function ()
{
//MYAPPLICATION.myJSON = JSON.stringify(MYAPPLICATION.Names);
var i, len, str;
for(i = 0, len = MYAPPLICATION.Names.length, str = ""; i < len; ++i)
{
if (!isNaN(MYAPPLICATION.Names[i])) { continue; }
str += MYAPPLICATION.Names[i] + "<br>";
}
console.log(document.getElementById("content").innerHTML = str);
}
You can also remove the console.log if you don't want to print in the console.
Like:
var MYAPPLICATION = MYAPPLICATION || {};
MYAPPLICATION.Names = ["Superman", "Batman", "Flash", 66, 23, 97]
MYAPPLICATION.DisplayNames = function ()
{
var i, len, str;
for(i = 0, len = MYAPPLICATION.Names.length, str = ""; i < len; ++i)
{
name = MYAPPLICATION.Names[i]
if (!isNaN(name)) { continue; }
str += name + "<br>";
}
document.getElementById("content").innerHTML = str;
}

MYAPPLICATION.DisplayNames = function () {
var stringsOnly = MYAPPLICATION.Names.filter(function(item) {
return typeof item === 'string';
});
document.getElementById("content").innerHTML = stringsOnly.join('<br>');
}

Related

Lua table to js array

I have a lua table like
Save = {
["player 1"] = {
["show"] = true,
["name"] = "user1",
["data"] = 56171308,
},
["player 2"] = {
["show"] = false,
["name"] = "user1",
["data"] = 508703367,
},}
And i want to convert it to a js array through an html page to look like
[ ["player 1","user1",56171308],
["player 2","user2",508703367] ]
I have tried to load the lua content on page and remove some elements with this function
<script>
function myFunction() {
var str = document.getElementById("file-content").innerHTML;
var res = str.replace(/Save|show|true|false|name|data|,|{|}|=|"|[[\]]/g, '');
var temp = new String(res);
temp = temp.replace(/^\s*[\r\n]/gm, '');
document.getElementById("file-content").innerHTML = temp;
}
</script>
Here is updated answer for you issue:
function myFunction() {
var str = document.getElementById("file-content").innerHTML;
var res = str.replace(/Save|show|true|false|name|data|,|{|}|=|"|[[\]]/g, ' '); // extra white space replace
var temp = new String(res);
temp = temp.replace(/^\s*[\r\n]/gm, '');
temp = temp.replace(/(\r\n|\n|\r)/gm, "");
temp = temp.replace(/\t/g, '');
var array = temp.split(" ");
array = array.filter(function(e) {
return e
});
var finalArray = chunkArray(array, 3)
console.log(finalArray);
var longstring = convertToSring(finalArray);
document.getElementById("file-content").innerHTML = longstring.toString();
}
function chunkArray(myArray, chunk_size) {
var index = 0;
var arrayLength = myArray.length;
var tempArray = [];
for (index = 0; index < arrayLength; index += chunk_size) {
myChunk = myArray.slice(index, index + chunk_size);
// Do something if you want with the group
tempArray.push(myChunk);
}
return tempArray;
}
function convertToSring(finalArray) {
var longstring = "[";
for (var i = 0; i < finalArray.length; i++) {
var string = '["' + finalArray[i].join('","') + '"],';
console.log(string);
longstring = longstring + string;
}
longstring = longstring.replace(/,\s*$/, ""); // remove last comma
longstring = longstring + "]";
return longstring;
}
myFunction();
Check the jsfiddle working code : https://jsfiddle.net/gcfs0kda/2/

How could i get the result as trie format? object to string format from this code.

My expected output is ["Mark", "Mary", "Martod", "Mariam", "Marg"]
Getting output in console is ["Mark", "Mary", "Mart", "Mari", "Marg"]
How could I get the output as my expected result from this code? Can anyone do this for me?
function get_suggestion_array_from_object(searchstring, current_object) {
var suggestion_array = [];
suggestion_array.push(searchstring);
// console.log(suggestion_array);
append_object_key(suggestion_array, current_object);
}
var test_searchstring = 'Mar';
var test_current_object_string = '{"k":0,"y":0,"t":{"o":{"d":0}},"i":{"a":{"m":0}},"g":0}';
var test_current_object = JSON.parse(test_current_object_string);
console.log(test_current_object);
get_suggestion_array_from_object(test_searchstring, test_current_object);
function append_object_key(suggestion_array, current_object) {
var keys = Object.keys(current_object);
// CONCATENATE WITH SUGGESTION ARRAY ELEMENTS
var new_suggestion_array = [];
for (var i = 0; i < keys.length; i++) {
var current_key = keys[i];
var array_to_push = suggestion_array.slice();
for (var j = 0; j < suggestion_array.length; j++) {
array_to_push[j] = array_to_push[j] + current_key;
}
new_suggestion_array = new_suggestion_array.concat(array_to_push);
}
console.log(new_suggestion_array);
}
There are several approaches:
const get_suggestion_array_from_object = (searchstring, current_object_string) =>
current_object_string
.split(/[^a-z]+0[^a-z]+/)
.reduce((a, e) => e && a.concat(searchstring + e.replace(/[^a-z]+/g, '')) || a, [])
let searchstring = 'Mar';
let current_object_string = '{"k":0,"y":0,"t":{"o":{"d":0}},"i":{"a":{"m":0}},"g":0}';
console.log(get_suggestion_array_from_object(searchstring, current_object_string));
...
var test_searchstring = 'Mar';
var test_current_object_string = '{"k":0,"y":0,"t":{"o":{"d":0}},"i":{"a":{"m":0}},"g":0}';
var test_current_object = JSON.parse(test_current_object_string);
function get_suggestion_array_from_object(s, o) {
return Object.keys(o).map(function(k) {
var e = k;
var no = o[k];
while (no) {
var nk = Object.keys(no)[0];
e += nk;
no = no[nk];
}
return s + e;
})
}
console.log(get_suggestion_array_from_object(test_searchstring, test_current_object))

Create Array of Objects and count number of occurrence

I have an array of objects and want to create another array of objects based on.
I want to check if an object is repeated just want to show the count, otherwise show the object itself with count = 1.
<!-- I have an array-->
var arr =[{name:"coke",price:20},{name:"coke",price:20},{name:"coke",price:20},{name:"kabab",price:250}];
// I want to create another array based on "arr" like the one below
var test =[{name:"coke",price:20,count:3},{name:"kabab",price:20,count:1}];
//Any hint please
This may help you. This answer considers name or some identifier will be unique for each object.
counter = {}
var arr = [{
name: "coke",
price: 20
}, {
name: "coke",
price: 20
}, {
name: "coke",
price: 20
}, {
name: "kabab",
price: 250
}];
var obj = {};
var counter = {}
for (var i = 0, len = arr.length; i < len; i++) {
obj[arr[i]['name']] = arr[i];
counter[arr[i]['name']] = (counter[arr[i]['name']] || 0) + 1
}
newArr = new Array();
for (var key in obj){
newArr.push(extend( obj[key], {count:counter[key]}));
}
function extend(a, b){
for(var key in b)
if(b.hasOwnProperty(key))
a[key] = b[key];
return a;
}
console.log(newArr)
var arr =[{name:"coke",price:20},{name:"coke",price:20},{name:"coke",price:20},{name:"kabab",price:250}];
var countNameMapping = {}, finalArr = [];
var arrLength = arr.length;
for(i=0; i<arrLength; i++){
var tempObj = {name:arr[i], price:arr[i].price, occurance:1};
var productName = arr[i].name;
if(countNameMapping[productName] === undefined){
countNameMapping[productName] = tempObj;
}else{
countNameMapping[productName].occurance += 1;
}
}
for(var k in countNameMapping){
finalArr.push(countNameMapping[k])
}
console.log(finalArr );
You can try this one:
var arr =[{name:"coke",price:20},{name:"coke",price:20},{name:"coke",price:20},{name:"kabab",price:250}];
var result = [];
arr.map(function(arrObject) {
if (result.length > 0) {
result.map(function(resultObject) {
if (resultObject.name != arrObject.name) {
arrObject.count = 1;
result.push(arrObject);
} else {
resultObject.count++;
}
})
} else {
arrObject.count = 1;
result.push(arrObject);
}
})
console.log(result);
This will provide the result you are looking for:
var arr =[{name:"coke",price:20},{name:"coke",price:20},{name:"coke",price:20},{name:"kabab",price:250}];
var map = arr.reduce((accum, item) => {
var obj = accum.get(item.name) || Object.assign({}, item, {count:0});
obj.count++;
return accum.set(item.name, obj);
}, new Map());
var res = [...map.values()];
More or less...
var arr = [{
name: "coke",
price: 20
}, {
name: "coke",
price: 20
}, {
name: "coke",
price: 20
}, {
name: "kabab",
price: 250
}];
// I want to create another array based on "arr" like the one below
// var test =[{name:"coke",price:20,count:3},{name:"kabab",price:20,count:1}];
var count = {};
var test = [];
for (var i = 0, len = arr.length; i < len; i++) {
var id = JSON.stringify(arr[i]);
if (count.hasOwnProperty(id)) {
count[id].count++;
} else {
test.push(arr[i]); // Data contamination. Too lazy to copy object
count[id] = test[test.length - 1]; // Could be better.
count[id].count = 1;
}
}
console.log(test);
This is probably what are you looking for:
How does it work?
First, your array arr will use a forEach loop to find each object and if if new you will add it to the results array. The method isNew() will return true if the object is new.
For each new object founded you will count the number of occurrences using findOccurrences() To reduce the number of "loops" you will slice the array according to the index. So you don't need to search again over the already processed data.
So now you can build an new object, using the name, price and count.
Finally, you can push() the new object to the results array.
var arr =[{name:"coke",price:20},{price:20,name:"coke"},{name:"coke",price:20},{name:"kabab",price:250}];
var results = [];
var index = 0;
var originalDiv = document.getElementById('original');
var resultsDiv = document.getElementById('results');
arr.forEach(function(obj) {
if (isNew(obj)) {
var counter = findOccurrences(obj, arr.slice(index, arr.length));
var newObj = {
name: obj.name,
price: obj.price,
count: counter
}
results.push(newObj);
}
index++;
});
printArray(arr, originalDiv);
printArray(results, resultsDiv);
function isNew(newObj) {
var wasFound = true;
if (typeof results != "undefined" && results != null && results.length > 0) {
results.forEach(function(obj) {
if (newObj.name === obj.name && newObj.price === obj.price) {
return false;
} else {
wasFound = false;
}
});
return !wasFound;
} else {
return true;
}
}
function findOccurrences(newObj, objects) {
var count = 0;
if (typeof objects != "undefined" && objects != null && objects.length > 0) {
objects.forEach(function(obj) {
if (newObj.name === obj.name && newObj.price === obj.price) {
count++;
}
});
}
return count;
}
function printArray(objects, div) {
var count = 0;
if (typeof objects != "undefined" && objects != null && objects.length > 0) {
objects.forEach(function(obj) {
var newElement = document.createElement('p');
newElement.innerHTML = 'item ' + count + ': ';
Object.keys(obj).forEach(function(key) {
newElement.innerHTML += key + ': ' + obj[key] + ', ';
});
newElement.innerHTML = newElement.innerHTML.slice(0, -2);
div.appendChild(newElement);
count++;
});
}
}
<div id="original"><p>Original Array</p></div>
<div id="results"><p>Results Array</p></div>
Update:
More optimization.
var arr =[{name:"coke",price:20},{name:"coke",price:20},{name:"coke",price:20},{name:"kabab",price:250},{name:"coke",price:20},{name:"coke",price:20},{name:"kabab",price:250}];
var accumulator = {};
var results = [];
var index = 0;
var originalDiv = document.getElementById('original');
var resultsDiv = document.getElementById('results');
String.prototype.hashCode = function() {
var hash = 0;
if (this.length == 0) return hash;
for (i = 0; i < this.length; i++) {
var char = this.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash |= 0; // Convert to 32bit integer
}
var c = (hash & 0x0FFFFFFF)
.toString(16)
.toUpperCase();
return '0000000'.substring(0, 7 - c.length) + c;
};
arr.forEach(function(obj) {
var id = JSON.stringify(obj).hashCode();
console.log(id);
if (accumulator.hasOwnProperty(id)) {
accumulator[id].count++;
} else {
results.push(obj);
accumulator[id] = results[results.length - 1];
accumulator[id].count = 1;
}
});
printArray(arr, originalDiv);
printArray(results, resultsDiv);
function printArray(objects, div) {
var count = 0;
if (typeof objects != "undefined" && objects != null && objects.length > 0) {
objects.forEach(function(obj) {
var newElement = document.createElement('p');
newElement.innerHTML = 'item ' + count + ': ';
Object.keys(obj).forEach(function(key) {
newElement.innerHTML += key + ': ' + obj[key] + ', ';
});
newElement.innerHTML = newElement.innerHTML.slice(0, -2);
div.appendChild(newElement);
count++;
});
}
}
<div id="original">
<p>Original Array</p>
</div>
<div id="results">
<p>Results Array</p>
</div>

how to reindex object start from 0

I have an object output from below code how to set the index start from 0 in js?
Object
3: Object
id: 34
type: 0
var obj = {};
var edited = false;
for (var i = 0; i < $(".list").length; i++) {
var data_id = parseInt($(".list").eq(i).attr('data-id'));
var data_type = parseInt($(".list").eq(i).attr('data-type'));
if ((data_type != 0)) {
edited = true;
} else {
edited = false;
}
if (edited == true) {
obj[i] = {};
obj[i]['id'] = data_id;
obj[i]['type'] = data_type;
}
}
console.log(obj);
Needs more jQuery ?
var arr = $(".list").filter(function() {
return $(this).data('type') != 0;
}).map(function() {
return { id : $(this).data('id'), type : $(this).data('type') };
}).get();
FIDDLE
Actually if you want to start in 0, use another variable and not "i" (which I think is 3 when you use it as index).
var obj = {};
var edited = false;
var obj_idx = 0;
for (var i = 0; i < $(".list").length; i++) {
var data_id = parseInt($(".list").eq(i).attr('data-id'));
var data_type = parseInt($(".list").eq(i).attr('data-type'));
if ((data_type != 0)) {
edited = true;
} else {
edited = false;
}
if (edited == true) {
obj[obj_idx] = {};
obj[obj_idx]['id'] = data_id;
obj[obj_idx]['type'] = data_type;
obj_idx += 1;
}
}
console.log(obj);
I think this time obj will be something like:
Object
0: Object
id: 34
type: 0
you could fake object as array by Array.prototype.push.call, in that way you could also gain the side effect: obj.length. it's kinda ninja and elegant :]
var obj = {};
var edited = false;
for (var i = 0; i < $(".list").length; i++) {
var data_id = parseInt($(".list").eq(i).attr('data-id'));
var data_type = parseInt($(".list").eq(i).attr('data-type'));
if ((data_type != 0)) {
edited = true;
} else {
edited = false;
}
if (edited == true) {
Array.prototype.push.call(obj, {id: data_id, type: data_type});
}
}
I am going to give a very simple and readable example. Say you've got an object with the following structure:
Object
0: Object
key: 'some-key'
value: 'some-value'
1: Object
...
Then you might want to delete an entry from it and reindex the whole thing, this is how I do it:
// obj is Object from above
const reIndexed = Object.entries(obj).map((element, index) => {
if (parseInt(element[0] != index) {
element[0] = index.toString();
}
return element;
});

How to parse input[] values and put them into a Javascript Array

Let's say i have this:
<form id='foo'>
<input name='bar[name]' />
<input name='bar[age]' />
</form>
How can i get the values of array inputs within the form foo and put them into an associative array/object like this:
var result = {bar:{name:'blah',age:21}};
P.S. I don't want to use any frameworks for this.
I needed to do this myself and after finding this question I didn't like any of the answers: I don't like regex and the others are limited.
You can get the data variable many ways. I'll be using jQuery's serializeArray method when I implement this.
function parseInputs(data) {
var ret = {};
retloop:
for (var input in data) {
var val = data[input];
var parts = input.split('[');
var last = ret;
for (var i in parts) {
var part = parts[i];
if (part.substr(-1) == ']') {
part = part.substr(0, part.length - 1);
}
if (i == parts.length - 1) {
last[part] = val;
continue retloop;
} else if (!last.hasOwnProperty(part)) {
last[part] = {};
}
last = last[part];
}
}
return ret;
}
var data = {
"nom": "123",
"items[install][item_id_4]": "4",
"items[install][item_id_5]": "16",
"items[options][takeover]": "yes"
};
var out = parseInputs(data);
console.log('\n***Moment of truth:\n');
console.log(out);
You can map the elements to an object like this.
function putIntoAssociativeArray() {
var
form = document.getElementById("foo"),
inputs = form.getElementsByTagName("input"),
input,
result = {};
for (var idx = 0; idx < inputs.length; ++idx) {
input = inputs[idx];
if (input.type == "text") {
result[input.name] = input.value;
}
}
return result;
}
var form = document.getElementById( 'foo' );
var inputs = form.getElementsByTagName( "input" );
var regex = /(.+?)\[(.+?)\]/;
var result = {};
for( var i = 0; i < inputs.length; ++i ) {
var res = regex.exec( inputs[i].name );
if( res !== null ) {
if( typeof result[ res[1] ] == 'undefined' ) result[ res[1] ] = {};
result[ res[1] ][ res[2] ] = inputs[i].value;
}
}
var inputs = document.getElementsByTagName('input');
var field_name, value, matches, result = {};
for (var i = 0; i < inputs.length; i++) {
field_name = inputs[i].name;
value = inputs[i].value;
matches = field_name.match(/(.*?)\[(.*)\]/);
if (!results[matches[0]]) {
results[matches[0]] = {};
}
results[matches[0]][matches[1]] = value;
}
This will get you the elements:
var result = {};
var elements = document.forms.foo.getElementsByTagName("input");
for(var i = 0; i < elements.length; i++)
{
/* do whatever you need to do with each input */
}

Categories

Resources