Forcing javascript key integer fills array with null - javascript

I am creating an array in Javascript where the product id is used for the key. As the key is numeric, the array is filling gaps with null.
So for example, if I had only two products and their ids were 5 and 7, I would do something like:
var arr = []
arr[5] = 'my first product';
arr[7] = 'my second product';
This array is then passed to a PHP script but upon printing the array, I get the following;
Array (
[0] = null
[1] = null
[2] = null
[3] = null
[4] = null
[5] = My first product
[6] = null
[7] = My second product
)
my ID numbers are actually 6 digits long, so when looping over the array, there are 100,000 iterations, even if I actually only have two products.
How can I create the array so the null values are not entered? I thought of making the key a string instead but as the array is build dynamically, I am not sure how to do that.
var arr = [];
for(var i=0; i<products.length; i++)
{
array[products[i].id] = products[i].name;
}
Thanks

For iterating the array, you could use Array#forEach, which skips sparse items.
var array = [];
array[5] = 'my first product';
array[7] = 'my second product';
array.forEach(function (a, i) {
console.log(i, a);
});
For better organisation, you could use an object, with direct access with the given id.
{
5: 'my first product',
7: 'my second product'
}

Forcing javascript key integer fills array with null
You are declaring an empty array and then setting values into 6th and 8th element in the array. That leaves the values of other elements as null.
If you don't intend to push items into array, i.e. use objects. Something like,
var obj = {};
obj[5] = "my first product";
obj[7] = "my second product";
This means the object created is:
obj = {"5":"my first product","7":"my second product"}

var arr = []
arr[5] = 'my first product';
arr[7] = 'my second product';
let result = arr.filter(ar => ar != null);
console.log(result);

Related

How to enter a string to an array to a given position?

The condition is such that I have to enter a string to an array to a given position
such that all the pre position if not exist should be made to be empty strings.
example;
var array = []; // now I want to enter a string 'hello' at index 2
now the array should look like:
array = [ '','','hello']; //now lets say I want to enter a string 'world' at index 4
so the array should become:
array = [ '','','hello','','world'];
Is there a way to do this?
or do i have a better option to enter a string and and its position?
Please enlighten me.. :)
Something like this should do the trick. The function takes three arguments: the target array, the index (0-based) and the value. Just iterate from the finish of you array to the new position and add "" to each entry, then, after the loop, enqueue the desired string. Here's the fiddle.
let a = ['', '', 'Hello'];
function addStringAtPosition(
array,
key,
value
) {
for (let i = array.length; i < key; i++) {
array[i] = '';
}
array[key] = value;
}
addStringAtPosition(a, 5, 'World!');
First find out how many additional elements need to add ''
push these new elements to array.
push the required value at end.
PS: Assumed the index always higher than the array length. We can add conditions to cover those cases as well.
const insert = (arr, value, index) => {
arr.push(...new Array(index - arr.length).fill(""));
arr.push(value);
return arr;
};
const array = [];
insert(array, "hello", 2);
console.log(array);
insert(array, "world", 4);
console.log(array);

What is empty inside an array? e.g. [empty X 5]

Sorry for misleading title here, I wasn't able to frame any proper one.
I am confused in array when there is nothing inside them (prints by empty X n) but they have length.
e.g. I create array by const a = [,,,]. This creates an array whose length is 3 but nothing inside it. If i print it in browser console, it prints the following:
What does empty mean here? If I run map or forEach function and try to console something, I get nothing.
Have added some code.
const a = [,,,]
console.log("print a: ",a)
console.log("print a.length: ",a.length)
console.log("print typeof a[0]: ", typeof a[0])
console.log("a.forEach((data, index) => { console.log(data, index) }): ", a.forEach((data, index) => { console.log(data, index) }))
console.log("")
const b = [undefined, undefined, undefined]
console.log("print b: ", b)
console.log("print b.length: ", b.length)
console.log("print typeof b[0]: ", typeof b[0])
console.log("b.forEach((data, index) => { console.log(data, index) }): ", b.forEach((data, index) => { console.log(data, index) }))
console.log("")
console.log("compare a[0] and b[0]: ", a[0] === b[0])
The only thing which differs is when I print a and b (though stackoverflow console prints them same but browser console prints differently) and when I try to loop through the array. Also momentjs isEqual gives them equal (jsfiddle here)
My main doubts are:
What type of array is it?
What does empty mean here?
How is it different from array which has all undefined values or empty array? or is it not?
Do we use it or any sample use case for this one
I have read about null and undefined array values and have understood it. But for this one, I haven't find anything proper. Most of the search I found were related to const a = [] is an empty array or how to check if array is empty and so on.
So, if someone can explain or give any proper links to read, it will be very helpful.
Please let me know, if I should add anything else.
Intro to sparse arrays
First a clarification what you've created is called a sparse array. To put it simply, sparse arrays are similar to normal arrays but not all of their indexes have data. In some cases, like JavaScript, this leads to slightly more significant handling of them. Other languages simply have a normal array of fixed length with some values that are "zero" in some sense (depends on what value can signify "nothing" for a specific array - might be 0 or null or "", etc).
Empty slots
The empty slot in a sparse array is exactly what it sounds like - slot that is not filled with data. JavaScript arrays unlike most other implementations, are not fixed size and can even have some indexes simply missing. For example:
const arr = []; // empty array
arr[0] = "hello"; // index 0 filled
arr[2] = "world"; // index 2 filled
You will get an array with no index 1. It's not null, nor it's empty, it's not there. This is the same behaviour you get when you have an object without a property:
const person = {foo: "hello"};
You have an object with a property foo but it doesn't have, for example, a bar property. Exactly the same as how the array before doesn't have index 1.
The only way JavaScript represents a "value not found" is with undefined, however that conflates
"the property exists and the value assigned to it is undefined"
"the property does not exist at all"
Here as an example:
const person1 = { name: "Alice", age: undefined };
const person2 = { name: "Bob" };
console.log("person1.age", person1.age);
console.log("person2.age", person2.age);
console.log("person1.hasOwnProperty('age')", person1.hasOwnProperty('age'));
console.log("person2.hasOwnProperty('age')", person2.hasOwnProperty('age'));
You get undefined when trying to resolve age in either case, however the reasons are different.
Since arrays in JavaScript are objects, you get the same behaviour:
const arr = []; // empty array
arr[0] = "hello"; // index 0 filled
arr[2] = "world"; // index 2 filled
console.log("arr[1]", arr[1]);
console.log("arr.hasOwnProperty(1)", arr.hasOwnProperty(1));
Why it matters
Sparse arrays get a different treatment in JavaScript. Namely, array methods that iterate the collection of items will only go through the filled slots and would omit the empty slots. Here is an example:
const sparseArray = []; // empty array
sparseArray[0] = "hello"; // index 0 filled
sparseArray[2] = "world"; // index 2 filled
const arr1 = sparseArray.map(word => word.toUpperCase());
console.log(arr1); //["HELLO", empty, "WORLD"]
const denseArray = []; // empty array
denseArray[0] = "hello"; // index 0 filled
denseArray[1] = undefined; // index 1 filled
denseArray[2] = "world"; // index 2 filled
const arr2 = denseArray.map(word => word.toUpperCase()); //error
console.log(arr2);
As you can see, iterating a sparse array is fine, but if you have an explicit undefined, in the array, then word => word.toUpperCase() will fail because word is undefined.
Sparse arrays are useful if you have numerically indexed data that you want to run .filter, .find, .map, .forEach and so on. Let's illustrate again:
//some collection of records indexed by ID
const people = [];
people[17] = { id: 17, name: "Alice", job: "accountant" , hasPet: true };
people[67] = { id: 67, name: "Bob" , job: "bank teller", hasPet: false };
people[3] = { id: 3 , name: "Carol", job: "clerk" , hasPet: false };
people[31] = { id: 31, name: "Dave" , job: "developer" , hasPet: true };
/* some code that fetches records */
const userChoice = 31;
console.log(people[userChoice]);
/* some code that transforms records */
people
.map(person => `Hi, I am ${person.name} and I am a ${person.job}.`)
.forEach(introduction => console.log(introduction));
/* different code that works with records */
const petOwners = people
.filter(person => person.hasPet)
.map(person => person.name);
console.log("Current pet owners:", petOwners)
its just what it is empty its neither undefined or null
const a = [,,,,] is same as const a = new Array(4)
here a is an array with no elements populated and with only length property
do this, let arr1 = new array() and then console.log(arr1.length) you'll get 0 as output. and if you do console.log(arr1) you'll get [ <4 empty items> ]
if you change the length property of arr1 like this arr1.length = 4 you will have an empty array with it's length property = 4, but no items are populated so those slot will be empty and if you do console.log(typeof(arr1[0]) you get undefined only because there is no other possible types to show. And no methods of Array will be applied with an array with empty elements
so,
Empty array means an array with length property and with unpopulated slots
this is different from arrays with undefined because in JS undefined is a type and you can execute and have results by calling all array methods on it, whereas an array with empty elememts have no type and no array methods can be applied on it.

Remove duplicate index value from first array, manipulate second as per first(at some specific conditions)

This is the tricky one :
please understand my scenario:
I have two array , both array will have equal length always.
I want remove duplicate value in first array and second array will be manipulated according first one.
like if i have array like :
var firstArr = [1,1,4,1,4,5]
var secArr = ['sagar', 'vilas', 'suraj', 'ganesh','more','abhi']
//I want below Output
//[1,4,5] // this is firstArr after manipulation
//['sagar|vilas|ganesh','suraj|more',abhi] // this is secArr after manipulation
// here all duplicate values will be removed from first array
// and at same index second array will be manipulated.
please check my fiddle:
https://jsfiddle.net/abhilash503001/du4fe8ob/86/
You can use Map and reduce
First loop through the first array and map it values as key and take the values from second array's respective index as key
Now you have loop on the map's entries take the key's will be your unique firstArr and to get desired value for second arr you need to join values by |
var firstArray = [1,1,4,1,4,5]
var secArr = ['sagar', 'vilas', 'suraj', 'ganesh','more','abhi']
let op = firstArray.reduce((op,inp,index) => {
if(op.has(inp)){
let val = op.get(inp)
val.push(secArr[index])
op.set(inp, val)
} else {
op.set(inp,[secArr[index]])
}
return op
},new Map())
let {firstArr, secondArr} = [...op.entries()].reduce((op,[first,second])=>{
op.firstArr.push(first)
op.secondArr.push(second.join('|'))
return op
},{firstArr:[],secondArr:[]})
console.log(firstArr)
console.log(secondArr)
This is how I did it.
You first group the texts into arrays and then join them together.
var index_array = [1,1,4,1,4,5]
var text_array = ['sagar', 'vilas', 'suraj', 'ganesh','more','abhi'];
var manipulated_text_array = [];
var manipulated_index_array = [];
var groups = {};
for (let index in index_array) {
if (groups[index_array[index]] == undefined) {
groups[index_array[index]] = [];
}
groups[index_array[index]].push(text_array[index]);
}
for (let index in groups) {
manipulated_text_array.push(groups[index].join("|"));
}
manipulated_index_array = Object.keys(groups).map(x => parseInt(x));
console.log("texts", manipulated_text_array);
console.log("indexes", manipulated_index_array);

Javascript is empty after filling with data

Javascript array is empty after filling with values
I tried this code:
var browserdata = new Array();
// Fill the array with values
browserdata["qqq"] = "zzz";
browserdata["rrr"] = 1;
console.log(browserdata); // This shows an empty array
It should show { "qqq" => "zzz", "zzz" => 1 }
Actual output is [] (empty array).
You need to use Object data type instead of Array. Using object structure, you can assign properties to it and corresponding value for that property to get the desired output as { "qqq" => "zzz", "zzz" => 1 }
var browserdata = {};
// Fill the object with values
browserdata["qqq"] = "zzz";
browserdata["rrr"] = 1;
console.log(browserdata);
You can also use the another approach, to assign the property at the time object is declared:
var browserdata = {
'qqq': 'zzz',
'rrr': 1
};
console.log(browserdata);
It will never return empty as there are data in the array, with your code it will return an output
[qqq: "zzz", rrr: 1]
If you want to get an output like { "qqq" => "zzz", "zzz" => 1 } , You should use objects .Objects are nothing but a grouping of data,
for example, consider a student array with different data sets.
here you could define individual data or data sets like
student['name'] = john ;
student['mark'] = 20;
OR
students =[{name : john , mark :20} ,{name : rick, mark :20} ]
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
https://javascript.info/array
If new Array() is called with a single argument which is a number, then it creates an array without items, but with the given length.
It’s rarely used, because square brackets [] are shorter. Also there’s a tricky feature with it lets see.
var arr = new Array(2); // will it create an array of [2] ?
console.log( arr[0] ); // undefined! no elements.
console.log( arr.length ); // length 2
var browserdata = new Array();
browserdata[0] = "zzz";
browserdata[1] = 1;
console.log(browserdata);
console.log(browserdata.length);
That solution works for me. Initializing with {} rather than [] or new Array() works. Thanks.
var browserdata = {};
// Fill the object with values
browserdata["qqq"] = "zzz";
browserdata["rrr"] = 1;
console.log(browserdata);
Only the positive integer keys of array object are displayed by default, but the rest of the properties can still be accessed and seen in the Google Chrome console.
var arr = []
arr[1] = 1
arr[-1] = -1
arr[.1] = .1
arr.a = 'a'
arr['b'] = 'b'
console.log( arr ) // [undefined, 1]
console.log( arr.b ) // "b"
console.log( { ...arr } ) // { "1": 1, "-1": -1, "0.1": 0.1, "a": "a", "b": "b" }

Using an integer as a key in an associative array in JavaScript

When I create a new JavaScript array, and use an integer as a key, each element of that array up to the integer is created as undefined.
For example:
var test = new Array();
test[2300] = 'Some string';
console.log(test);
will output 2298 undefined's and one 'Some string'.
How should I get JavaScript to use 2300 as a string instead of an integer, or how should I keep it from instantiating 2299 empty indices?
Use an object, as people are saying. However, note that you can not have integer keys. JavaScript will convert the integer to a string. The following outputs 20, not undefined:
var test = {}
test[2300] = 20;
console.log(test["2300"]);
You can just use an object:
var test = {}
test[2300] = 'Some string';
As people say, JavaScript will convert a string of number to integer, so it is not possible to use directly on an associative array, but objects will work for you in similar way I think.
You can create your object:
var object = {};
And add the values as array works:
object[1] = value;
object[2] = value;
This will give you:
{
'1': value,
'2': value
}
After that you can access it like an array in other languages getting the key:
for(key in object)
{
value = object[key] ;
}
I have tested and works.
If the use case is storing data in a collection then ECMAScript 6 provides the Map type.
It's only heavier to initialize.
Here is an example:
const map = new Map();
map.set(1, "One");
map.set(2, "Two");
map.set(3, "Three");
console.log("=== With Map ===");
for (const [key, value] of map) {
console.log(`${key}: ${value} (${typeof(key)})`);
}
console.log("=== With Object ===");
const fakeMap = {
1: "One",
2: "Two",
3: "Three"
};
for (const key in fakeMap) {
console.log(`${key}: ${fakeMap[key]} (${typeof(key)})`);
}
Result:
=== With Map ===
1: One (number)
2: Two (number)
3: Three (number)
=== With Object ===
1: One (string)
2: Two (string)
3: Three (string)
Compiling other answers:
Object
var test = {};
When using a number as a new property's key, the number turns into a string:
test[2300] = 'Some string';
console.log(test['2300']);
// Output: 'Some string'
When accessing the property's value using the same number, the number is turned into a string again:
console.log(test[2300]);
// Output: 'Some string'
When getting the keys from the object, though, they aren't going to be turned back into numbers:
for (var key in test) {
console.log(typeof key);
}
// Output: 'string'
Map
ECMAScript 6 allows the use of the Map object (documentation, a comparison with Object). If your code is meant to be interpreted locally or the ECMAScript 6 compatibility table looks green enough for your purposes, consider using a Map:
var test = new Map();
test.set(2300, 'Some string');
console.log(test.get(2300));
// Output: 'Some string'
No type conversion is performed, for better and for worse:
console.log(test.get('2300'));
// Output: undefined
test.set('2300', 'Very different string');
console.log(test.get(2300));
// Output: 'Some string'
Use an object instead of an array. Arrays in JavaScript are not associative arrays. They are objects with magic associated with any properties whose names look like integers. That magic is not what you want if you're not using them as a traditional array-like structure.
var test = {};
test[2300] = 'some string';
console.log(test);
Try using an Object, not an Array:
var test = new Object(); test[2300] = 'Some string';
Get the value for an associative array property when the property name is an integer:
Starting with an associative array where the property names are integers:
var categories = [
{"1": "Category 1"},
{"2": "Category 2"},
{"3": "Category 3"},
{"4": "Category 4"}
];
Push items to the array:
categories.push({"2300": "Category 2300"});
categories.push({"2301": "Category 2301"});
Loop through the array and do something with the property value.
for (var i = 0; i < categories.length; i++) {
for (var categoryid in categories[i]) {
var category = categories[i][categoryid];
// Log progress to the console
console.log(categoryid + ": " + category);
// ... do something
}
}
Console output should look like this:
1: Category 1
2: Category 2
3: Category 3
4: Category 4
2300: Category 2300
2301: Category 2301
As you can see, you can get around the associative array limitation and have a property name be an integer.
NOTE: The associative array in my example is the JSON content you would have if you serialized a Dictionary<string, string>[] object.
Simple solution if you would rather use an array.
When adding the number just preface it with a letter.
e.g.
let ctr = 3800;
let myArray=[];
myArray["x" + ctr.toString()]="something";
myArray["x" + (ctr+1).toString()]="another thing";
Then just add the "x" in access routines that call the number as an index.
e.g.:
console.log( myArray["x3800"] );
or:
console.log( myArray["x"+ numberOfYourChoice.toString()] );
Use an object - with an integer as the key - rather than an array.
Sometimes I use a prefixes for my keys. For example:
var pre = 'foo',
key = pre + 1234
obj = {};
obj[key] = val;
Now you don't have any problem accessing them.

Categories

Resources