How do Object and some Key in square brackets work? - javascript

Can somebody explain how does seen[item] work?
var a = ["a","a","a","b","b","c","D","D","e",6,6,7,8,9,"a",'b','a',"c","","","",""];
function uniq_fast(a) {
var seen = {};
var out = [];
var len = a.length;
var j = 0;
for(var i = 0; i < len; i++) {
var item = a[i];
if(seen[item] !== 1) {
seen[item] = 1;
out[j++] = item;
}
}
return out;
}
var e = uniq_fast(a);
console.log(e);
It returns undefined everytime:
var a = [1,1,1,1,1,2,2,3,4,4,4,4,4,5,"a",'b','a',"c"];
for(var i = 0; i < a.length; i++) {
var seen = {};
var item = a[i];
var x = seen[item];
console.log(x);
}

I've added comments to your code, you can also check google Developer tools (or other browser equivalent) set breakpoint before for loop and go step by step to see the value of each variable.
var a = ["a","a","a","b","b","c","D","D","e",6,6,7,8,9,"a",'b','a',"c","","","",""];
function uniq_fast(a) {
var seen = {};
var out = [];
var len = a.length;
var j = 0;
// if i == 0;
for(var i = 0; i < len; i++) {
var item = a[i]; // item is "a" because that's first item in array
if(seen[item] !== 1) {
seen[item] = 1; // seen is {"a": 1} it's the same as seen['a'] = 1
out[j++] = item;
}
}
return out;
}
in your second code:
var a = ["a","a","a","b","b","c","D","D","e",6,6,7,8,9,"a",'b','a',"c","","","",""];
for(var i = 0; i < a.length; i++) {
var seen = {}; // you have empty object
var item = a[i]; // item is "a"
console.log(seen[item]); // this is undefined because seen["a"] is empty,
// you never adding anything to seen
}

In essence it's not more than
object['a'] = object.a

Related

how to get distinct value from an array javascript

how can i get elements uniquely from an array if aa is twice time it should not count in a result if it is if a is three times it should count 1
var string = "aaabbccddde" // Expected result ade
var toArray = string.split("")
console.log(toArray)
var newArr = []
for(let i =0; i<toArray.length; i++) {
if(newArr.indexOf(toArray[i]) === -1) {
newArr.push(toArray[i])
}
}
console.log(newArr)
can't find the solution yet please guide thank
Maybe this function can help you:
function getUniques(str) {
const uniques = [];
const strs = str.split("");
for (let i = 0; i < strs.length; i++) {
const elm = strs[i];
for (let j = i; j < strs.length; j++) {
if(elm === uniques[uniques.length - 1]) break;
if (elm !== strs[j + 1]) {
uniques.push(elm);
break;
}
}
}
return uniques.join("");
}
Sample:
getUniques("aaaadaaabbbcccdeeeee22222222222232") // adabcde232

Append element in JSobject

I am trying to create a JS object which has this structure
{ node1:
[ 'test1.1',
'test1.2'],
node2:
['test2.1',
'test2.2']
}
This is my code
for (var k = 0; k < keys.length; i++){
key = keys[k];
var result = {};
var r = [];
for (var i = 0; i < elements.length; i++){
r.push(elements[i]);
}
result[key] = r;
}
the result looks a bit different from my expectation and is not a valid JSON:
{ node1:
[ 'test1.1',
'test1.2'] }
{ node2:
[ 'test2.1',
'test2.2' ] }
I am not sure what is wrong about the code.
Declare var result = {}; outside the for loop and it will work as currently a new object is created inside the loop.
var result = {};
for (var k = 0; k < keys.length; k++) {
key = keys[k];
var r = [];
for (var i = 0; i < elements.length; i++) {
r.push(elements[i]);
}
result[key] = r;
}
You also have i++ in the first loop so change that to k++ otherwise there will be a infinite loop.

Defining a 3D array in JavaScript

I tried to define a 3D array on Google Sheet, but even though I'm using the .slice() method it keeps passing the array by reference.
var temp = [];
for (var a = 0; a<archetypesAll.length; a++) {temp[a] = [0, a].slice();};
var archRank = [];
for (var a = 0; a<21; a++) {archRank[a]= temp.slice();};
archRank[2][1][0] = 'Test';
I want to edit a single element of the matrix but instead the code above just fills every row with the exact same value ('Test'):
3DMatrix[x][1][0] = 'Test'
You can't just copy a multidimensional array by calling slice at the top level, because that will not deep-copy the whole. You have to write your own deepCopy methid, like this:
function allocate(mainDim, ...dims) {
const result = new Array(mainDim);
for (let i = 0; i < result.length; i++) {
result[i] = dims.length > 0 ? allocate(...dims) : 0;
}
return result;
}
function deepCopy(matrix, dims) {
return dims > 1 ? matrix.map(row => deepCopy(row, dims - 1)) : matrix.slice();
}
function test() {
const mx1 = allocate(3,2,2);
mx1[2][1][0] = "Test";
console.log(JSON.stringify(mx1));
const mx2 = deepCopy(mx1, 3);
mx2[2][1][0] = "Copied";
console.log(JSON.stringify(mx1));
console.log(JSON.stringify(mx2));
}
test();
var array = ["Test", "Test"];
var array3d = [[array.slice(0)],[[array.slice(0)]]];
array3d[0][0][0] = "Changed";
console.log(JSON.stringify(array3d)); //[[["Changed","Test"]],[[["Test","Test"]]]]
Try with this instead of slice to get a new array instead of reference:
var temp = [];
for (var a = 0; a < archetypesAll.length; a++) {
temp[a] = JSON.parse(JSON.stringify([0, a]));
}
var archRank = [];
for (var a = 0; a < 21; a++) {
archRank[a]= temp.slice();
}
archRank[2][1][0] = 'Test';

Alternately Join 2 strings - Javascript

I have 2 strings and I need to construct the below result (could be JSON):
indexLine: "id,first,last,email\n"
dataLine: "555,John,Doe,jd#gmail.com"
Result: "id:555,first:john,....;
What would be the fastest way of joining alternately those 2 strings?
I wrote this - but it seems too straight forward:
function convertToObject(indexLine, dataLine) {
var obj = {};
var result = "";
for (var j = 0; j < dataLine.length; j++) {
obj[indexLine[j]] = dataLine[j]; /// add property to object
}
return JSON.stringify(obj); //-> String format;
}
Thanks.
var indexLine = "id,first,last,email";
var dataLine = "555,John,Doe,jd#gmail.com";
var indexes = indexLine.split(',');
var data = dataLine.split(',');
var result = [];
indexes.forEach(function (index, i) {
result.push(index + ':' + data[i]);
});
console.log(result.join(',')); // Outputs: id:555,first:John,last:Doe,email:jd#gmail.com
If you might have more than one instance of your object to create, you could use this code.
var newarray = [],
thing;
for(var y = 0; y < rows.length; y++){
thing = {};
for(var i = 0; i < columns.length; i++){
thing[columns[i]] = rows[y][i];
}
newarray.push(thing)
}
source

Array by Reference vs Array by Value in Javascript

I'm reading Data Structures and Algorithms with Javascript by O'reily and it states the following:
Shallow copy (two arrays point to the same location in memory):
var nums = [];
for (var i = 0; i < 100; ++i) {
nums[i] = i+1;
}
var samenums = nums;
nums[0] = 400;
print(samenums[0]); // displays 400
Deep copy:
function copy(arr1, arr2) {
for (var i = 0; i < arr1.length; ++i) {
arr2[i] = arr1[i];
}
}
Now the following code fragment produces the expected result:
var nums = [];
for (var i = 0; i < 100; ++i) {
nums[i] = i+1;
}
var samenums = [];
copy(nums, samenums);
nums[0] = 400;
print(samenums[0]); // displays 1
Why is a function required in order to create deep copies?
As stated in the comments, the function is purely for aesthetics and reusability, and is not strictly necessary.
You could refactor your example:
function copy(arr1, arr2) {
for (var i = 0; i < arr1.length; ++i) {
arr2[i] = arr1[i];
}
}
var nums = [];
for (var i = 0; i < 100; ++i) {
nums[i] = i+1;
}
var samenums = [];
copy(nums, samenums);
nums[0] = 400;
print(samenums[0]); // displays 1
into this equivalent function-less example:
var nums = [];
for (var i = 0; i < 100; ++i) {
nums[i] = i+1;
}
var samenums = [];
for (var i = 0; i < nums.length; ++i) {
samenums[i] = nums[i];
}
nums[0] = 400;
print(samenums[0]); // displays 1

Categories