String view of file array in Javascript - javascript

I have an array of files in Javascript. How can I create a string with their names and sizes?
Example:
[ {File1} {File2} ] => "File: my_file1 size: size1 bytes, "File: my_file2 size: size2 bytes".
Not using for - I want to use functions :)
If use for it could be something like this
function createStringForFileArray(arr){
let result = "";
for (let i = 0; i <arr.length; i++ ){
result+= "File"+arr[i].name+" size "+arr[i].size+" ";
}
return result;
}

Iterate using Array#map and create a string for each file, then join all the strings:
const files = [{ name: 'file1', size: 1111 }, { name: 'file2', size: 2222 }];
const result = files.map(({ name, size }) => `File: ${name} size: ${size} bytes`).join(', ');
console.log(result);

You can simply use Array.prototype.reduce() to return a unique string from all your array elements.
Your code would be like this:
function createStringForFileArray(arr) {
return arr.reduce(function(a, b, i){
return a + "File: " + b.name + " size: " + b.size + (i !== array.length - 1 ? ", " : "");
}, "");
}
Demo:
This is a working Demo:
var array = [{
name: "file1",
size: "500Mb"
},
{
name: "Test",
size: "0Kb"
}, {
name: "TAnother File",
size: "30Kb"
}
];
function createStringForFileArray(arr) {
return arr.reduce(function(a, b, i){
return a + "File: " + b.name + " size: " + b.size + (i !== array.length - 1 ? ", " : "");
}, "");
}
console.log(createStringForFileArray(array));
Or you can use .map() function like this:
function createStringForFileArray(arr) {
return array.map(function(f) {
return "File: " + f.name + " size:" + f.size;
}).join(", ");
}

You could try map with reduce:
let str = files
.map(f => "File: " + f.name + " size: " + f.size)
.reduce((prev, curr) => prev + ", " + curr);
Edit: You can do it with just reduce. The original solution by #chsdk did this and was posted before mine, but it had an error (now corrected). So you may want to accept that answer instead.
let str = files.reduce((prev, curr, index, arr) => {
return prev + "File: " + curr.name + " size: " + curr.size + (index === arr.length - 1 ? "" : ", ");
}, "");

Related

Is there a way where I could put a line break for each data it displays?

I have this array and I can already display it on the screen. I'm wondering if I can put a line break for each of the data it displays.
{
name: "cartItems",
label: "Product Name",
options: {
filter: true,
sort: true,
customBodyRender: (value, tableMeta, updateValue) => {
// console.log(value, "cartItems");
return value.map(
(value) =>
value.name +
" (" +
value.color +
") - " +
" Qty:" +
value.quantity +
","
);
}
}
}
As of now, it displays in one line like this:
Item name (item color) - Qty: 1
Item name (item color) - Qty: 2
Item name (item color) - Qty: 2
I wanted to somehow display it like this:
Item name (item color) - Qty: 1
Item name (item color) - Qty: 2
Item name (item color) - Qty: 2
Is this possible?
Try to add \n
return value.map(
(value) =>
value.name +
" (" +
value.color +
") - " +
" Qty:" +
value.quantity +
"," +
"\n"
);
Try this :
return value.map((value) => `${value.name} (${value.color}) - Qty: ${value.quantity},
`);

how to convert an array to string including space elements in JS?

I want to convert this array into string includes space elements in javascript. space doesn't show after return.
let results = ['Hello',' ',' ',' ','EveryOne',' ',' ',' ','My',' ','Name',' ','is',' ','X'];
const result = () =>
{
for(let i = 0; i<results.length; i++)
{
return results;
}
}
result();
// Expected Output : "Hello EveryOne My Name is X";
use Array.prototype.join with empty string as separator:
const result = () => {
let results = ['Hello',' ',' ',' ','EveryOne',' ',' ',' ','My',' ','Name',' ','is',' ','X'];
return results.join('')
}
console.log(result())
You need to concatenate the elements in the for-loop:
const result = (results=[]) => {
let str = '';
for(let i = 0; i < results.length; i++) {
str += results[i];
}
return str;
}
console.log( result(['Hello',' ',' ',' ','EveryOne',' ',' ',' ','My',' ','Name',' ','is',' ','X']) );
Another way using .join:
const result = (results=[]) => {
return results.join('');
}
console.log( result(['Hello',' ',' ',' ','EveryOne',' ',' ',' ','My',' ','Name',' ','is',' ','X']) );
Since reactjs tag is there, am assuming issue rendering. Use HTML entity   for ' ', that should display correct as in snippet.
const Component = () => {
let results = [
"Hello",
" ",
" ",
" ",
"EveryOne",
" ",
" ",
" ",
"My",
" ",
"Name",
" ",
"is",
" ",
"X",
];
return (
<div>
{" "}
{results.map((word) => (
word === ' ' ? <span> </span> : <span> { word } </span>
))}{" "}
</div>
);
};
ReactDOM.render(<Component />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"> </div>
You can convert your array to string, and then split commas per something like: results.toString().split(',').join('');
let result = arr.filter(item => {
if (item !== " "){
return item
};
});
console.log("result",result)

How to print key and values from dictionaries enlisted in array, javascript

I am having difficulties printing data from dictionaries stored in an array using double for-loop with
var residents = [{name: "Pyrus", room: "32"},{name: "Ash Ketchum", room: "22"}];
function people() {
for (let i = 0; i < residents.length; i++) {
for (let j in residents[i]) {
document.write(j + ": " + residents[j] + "<br>");
}
}
};
people();
What I am retrieving is this:
name: undefined
room: undefined
name: undefined
room: undefined
I can print the key but it seems like it does not fetch value defined to the key!
What am I doing wrong?
A success criteria is to print in HTML.
You have chained two loops together so your function needs to access the parents index then the property that you wish to reference.
function people() {
for (let i = 0; i < residents.length; i++) {
for (let j in residents[i]) {
document.write(j + ": " + residents[i][j] + "<br>");
}
}
};
This is the simplest way I think(Use foreach()):
var residents = [{name: "Pyrus", room: "32"},{name: "Ash Ketchum", room: "22"}];
function people() {
residents.forEach(function(resident) {
document.write(resident.name + ": " + resident.room + "<br>");
});
}
people();
why not try like this with forEach()
var residents = [{
name: "Pyrus",
room: "32"
}, {
name: "Ash Ketchum",
room: "22"
}];
function people(residents) {
residents.forEach((element) => {
for (var key in element) {
if (element.hasOwnProperty(key)) {
console.log(key + ':' + element[key]);
}
}
});
};
people(residents);
You can avoid some of the for loops and make the code a little easier to read using forEach and Object.entries:
var residents = [{name: "Pyrus", room: "32"},{name: "Ash Ketchum", room: "22"}];
residents.forEach(res => {
Object.entries(res).forEach(([key, value]) => {
console.log(key + ": " + value ); //subing console.log so it prints here
//document.write(key + ": " + value + "<br>");
})
})
Using a regular for-loop it would go like the below code. Also, I strongly recommend you to check if all the properties (j) are own properties (with hasOwnProperty), otherwise this will look up in the prototype chain. This can be a problem if the objects are added to the array dynamically, otherwise you can bypass this check.
var residents = [{name:"Pyrus",room:"32"},{name: "Ash Ketchum",room:"22"}];
function people() {
for (let i = 0; i < residents.length; i++) {
for (let j in residents[i]) {
if (residents[i].hasOwnProperty(j)) { // <-- check if it is an own property!
document.write(j + ": " + residents[i][j] + "<br>");
//first access the object in residents[i], for example {name: "Pyrus",room: "32"}, then to its properties-values with residents[i][j]
}
}
}
};
people();
You need to access residents[i][j] since you are iterating residents in the first place.
so your code becomes :
document.write(j + ": " + residents[i][j] + "<br>");
See this working js fiddle
You could also write it like this :
function people(){
residents.forEach(r => {
for(let j in r){
document.write(j + ": " + r[j] + "<br>");
}
})
}
Hope this helps.

Javascript forEach() through an array: how to get the previous and next item?

Let's say we have an array of objects like:
var fruits = [ {name:"banana", weight:150},{name:"apple", weight:130},{name:"orange", weight:160},{name:"kiwi", weight:80} ]
I want to iterate through fruits and tell each time the name of the current, the previous and the next fruit.
I would do something like:
fruits.forEach(function(item,index) {
console.log("Current: " + item.name);
console.log("Previous: " + item[index-1].name);
console.log("Next: " + item[index-1].name);
});
But obviously it doesn't work for next and previous items...
Any idea?
Please note that I do not want to use the classic for loop
(for i=0; i
Thanks a lot!
Its not working because item is not an array so we cannot write item[index-1].name. Instead, we need to use fruits[index-1] .Also, the first element of the array will not have the previous item and the last element will not have next item.
Code snippet below should work for you.
var fruits = [{
name: "banana",
weight: 150
}, {
name: "apple",
weight: 130
}, {
name: "orange",
weight: 160
}, {
name: "kiwi",
weight: 80
}]
fruits.forEach(function(item, index) {
console.log("Current: " + item.name);
if (index > 0) {
console.log("Previous: " + fruits[index - 1].name);
}
if (index < fruits.length - 1) {
console.log("Next: " + fruits[index + 1].name);
}
});
Callback function in ForEach loop accepts the array as third parameter :
fruits.forEach((item, index, arr) => {
console.log("Current: " + item.name);
console.log("Previous: " + ((0 === index)? "START" : arr[index-1].name));
console.log("Next: " + ((arr.length - 1 === index)? "END" : arr[index+1].name));
});
For the first and last item, you can log END, or you can make it a carousel.
option 1: mark the start and the end:
fruits.forEach(function(item,index) {
console.log("Current: " + item.name);
console.log("Previous: " + (0 == index)? "START" : fruits[index-1].name);
console.log("Next: " + (fruits.length - 1 == index)? "END" : fruits[index+1].name);
});
option 2: carousel
fruits.forEach(function(item,index) {
console.log("Current: " + item.name);
console.log("Previous: " + (0 == index)? fruits[fruits.length - 1].name : fruits[index-1].name);
console.log("Next: " + (fruits.length - 1 == index)? fruits[0].name : fruits[index+1].name);
});
fruits.forEach(function(item,index) {
console.log("Current: " + item.name);
if (index > 0) {
console.log("Previous: " + fruits[index-1].name);
}
if (index < (fruits.length - 1)) {
console.log("Next: " + fruits[index+1].name);
}
});

How do I convert the object passed in to an array of strings

function objectToArray (object) {
var array = [];
var str = "";
for (var key in object) {
array.push(key);
array.push(object[key]);
if (object.hasOwnProperty(key)) {
str += key + " is " + object[key] + "";
}
}
console.log(array);
}
objectToArray({name: "Marcia", age: 101});
The output is [ 'name', 'Marcia', 'age', 101 ] and I need it to be ["name is Marcia", "age is 101"].
Instead of this:
array.push(key);
array.push(object[key]);
if (object.hasOwnProperty(key)) {
str += key + " is " + object[key] + "";
}
You want this:
if (object.hasOwnProperty(key)) {
array.push( key + " is " + object[key] + "" );
}
#VoteyDisciple has correctly pointed out where you went wrong with your approach. An alternate (shorter) way to implement your function is:
function objectToArray (object) {
return Object.keys(object).map(function (key) {
return key + " is " + object[key];
});
}
var arr = objectToArray({name: "Marcia", age: 101});
console.log(arr);

Categories