Array replacement javascript - javascript

i have two array:
array1 = [35,433]; array2 = [70,154,73];
Need to be arrays :
result[0] = [35,70]; result[1] = [35,154]; result[2] =
[35,73]; result[3] = [433,70]; result[4] = [433,154];
result[5] = [433,73];
My code:
var groupAttribute = [];
groupAttribute[0] = ['35'=>'bla','433'=>'blu'];
groupAttribute[1] = ['70'=>'fre','154'=>'nuy','73'=>'tres'];
var counter = 0;
var countAttributes = 5;
var combinat = [];
for (var i = 0, j = 0;; j++) {
if (i >= groupAttribute.length && j >= countAttributes) {
break;
}
if (i >= groupAttribute.length) {
i = 0;
}
combinat[counter] = [];
$.each(groupAttribute[i],function(key, attribute) {
combinat[counter].push(parseInt(key));
counter++;
i++;
});
}
console.log(combinat);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
Pls help me

Two separated array
var array1 = [35,433];
var array2 = [70,154,73];
var newArr = [];
array1.forEach(function(a) {
array2.forEach(function(b) {
newArr.push([a, b])
})
})
console.log(newArr)
If nested depth is unknown:
var arr = [[35,433], [70,154,73], [5,1]];
function Permute(arr) {
if (arr.length === 1) {
return arr[0];
}
var res = [];
var sliced = Permute(arr.slice(1));
arr[0].forEach(function(a) {
sliced.forEach(function(b) {
res.push([a].concat(b))
})
})
return res;
}
var newArr = Permute(arr);
console.log(newArr)
Hope this helps

Here's a purely function/recursive solution that works with any positive number of arrays.
let array1 = [35, 433];
let array2 = [70, 154, 73];
let array3 = [1, 2, 3];
let result = combine(array1, array2, array3 /* more arrays */ );
function combine(arr, ...rest) {
if (!rest.length) return arr.map(n => [n]);
const sub = combine(...rest);
return arr.reduce((a, n) => [...a, ...sub.map(a2 => [n, ...a2])], [])
}
console.log(result);
For the matrix diff you asked about in the comment, do this:
var arr1 = [[35,70],[433,70],[35,73],[433,73],[35,154],[433,154]];
var arr2 = [[433,70],[433,154],[433,73],[35,154]];
var result = [
...aNotInB(arr1, arr2),
...aNotInB(arr2, arr1),
];
function aNotInB(a, b) {
return a.filter(([x, y]) =>
!b.some(([x2, y2]) => x == x2 && y == y2)
)
}
console.log(result);

Related

How can I find the index of a 2d array of objects in javascript

So, what I'm trying to get is the index of a 2d array of objects, let's say I have the following
const arr = [
[{id: 1}, {id:2}],
[{id:3},{id:4},{id:5}]
]
If I'd want to get the index where id=3 it would be arr[1][0], Is there any way to achieve this using vanilla JS or any helper library?
You can achieve this by nesting two for loops.
function findNestedIndices(array, id) {
let i;
let j;
for (i = 0; i < array.length; ++i) {
const nestedArray = array[i];
for (j = 0; j < nestedArray.length; ++j) {
const object = nestedArray[j];
if (object.id === id) {
return { i, j };
}
}
}
return {};
}
const array = [
[{id: 1}, {id:2}],
[{id:3},{id:4},{id:5}]
];
const { i, j } = findNestedIndices(array, 3);
console.log(i, j); // 1, 0
Might be a more efficient way to do it, but you could accomplish this via array.findIndex:
const test = [
[{id: 1}, {id:2}],
[{id:3},{id:4},{id:5}]
];
function find(arr, id) {
const firstIndex = arr.findIndex(entry => entry.some(({id: x}) => x === id));
if (firstIndex > -1) {
const secondIndex = arr[firstIndex].findIndex(({ id: x }) => x === id );
return [firstIndex, secondIndex];
}
}
console.log(find(test, 2)); // [0, 1]
console.log(find(test, 4)); // [1, 1]
console.log(find(test, 5)); // [1, 2]
const arr = [
[{id: 1}, {id:2}],
[{id:3},{id:4},{id:5}]
];
let searchIndex = 3;
let x = arr.findIndex(sub => sub.find(el => el.id == searchIndex));
let y = arr[x].findIndex(el => el.id == searchIndex);
console.log(x, y)
const arr = [
[{id: 1}, {id:2}],
[{id:3},{id:4},{id:5}]
];
function getIndex(arr, value){
let rowIndex = null;
let valueIndex = null;
arr.forEach(( nestedArray, index) => {
if(!valueIndex) rowIndex = index;
nestedArray.every((val, valIndex) => {
if(val.id === value) {
valueIndex = valIndex;
return false
}
return true;
});
})
return {
rowIndex,
valueIndex
}
}
console.log(getIndex(arr, 3))

Fold a multi-dimensional array n:m in JavaScript [duplicate]

I have an Array. It contains several subgroups. Example:
let mainArray=[50,51,52,53,54,511,512,513,514,521,522,523,524,525,526,527]
I want to divide that main array into sub-arrays.For example
sub1 =[50,51,52,53,54]
sub2 =[511,512,513,514]
sub3 =[521,522,523,524,525,526,527]
Can you help me?
Use the Array reduce function :
let mainArray=[50,51,52,53,54,511,512,513,514,521,522,523,524,525,526,527];
let groups = mainArray.reduce (
(grps, el, i, main) => ((el === main[i-1] + 1 ? grps[0].push (el)
: grps.unshift ([el])), grps), []);
[sub3, sub2, sub1] = groups;
console.log (sub1, sub2, sub3);
This will create an Array of Subarays:
const arr = [50,51,52,53,54, 511,512,513,514, 521,522,523,524,525,526,527];
let newArr = [];
let temp = [arr[0]];
for (let index = 1; index < arr.length; index++) {
if (arr[index] == arr[index - 1] + 1) {
temp.push(arr[index]);
} else {
newArr.push(temp);
temp = [];
}
if (index == arr.length - 1) {
newArr.push(temp);
}
}
console.log(newArr)
var arr = [50,51,52,53,54,511,512,513,514,521,522,523,524,525,526,527];
var result = [],
lastVal = -1;
while(arr.length) {
var currentIndex = arr.length - 1;
var currentValue = arr[currentIndex];
var c = Math.floor(currentValue/10);
if (c !== lastVal) {
lastVal = c;
result.push([currentValue]);
}else{
result[result.length-1].push(currentValue);
}
arr.splice(currentIndex, 1);
}
result.forEach(function(arr){ arr.reverse(); });
console.log(result);
Here's a solution using Ramda.js
const x = [50,51,52,53,54,511,512,513,514,521,522,523,524,525,526,527]
const f = R.pipe(
R.sortBy(R.identity),
R.groupWith(R.pipe(R.subtract, Math.abs, R.equals(1)))
)
console.log(f(x))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>

How to separate each sub group in main group Array using javascript

I have an Array. It contains several subgroups. Example:
let mainArray=[50,51,52,53,54,511,512,513,514,521,522,523,524,525,526,527]
I want to divide that main array into sub-arrays.For example
sub1 =[50,51,52,53,54]
sub2 =[511,512,513,514]
sub3 =[521,522,523,524,525,526,527]
Can you help me?
Use the Array reduce function :
let mainArray=[50,51,52,53,54,511,512,513,514,521,522,523,524,525,526,527];
let groups = mainArray.reduce (
(grps, el, i, main) => ((el === main[i-1] + 1 ? grps[0].push (el)
: grps.unshift ([el])), grps), []);
[sub3, sub2, sub1] = groups;
console.log (sub1, sub2, sub3);
This will create an Array of Subarays:
const arr = [50,51,52,53,54, 511,512,513,514, 521,522,523,524,525,526,527];
let newArr = [];
let temp = [arr[0]];
for (let index = 1; index < arr.length; index++) {
if (arr[index] == arr[index - 1] + 1) {
temp.push(arr[index]);
} else {
newArr.push(temp);
temp = [];
}
if (index == arr.length - 1) {
newArr.push(temp);
}
}
console.log(newArr)
var arr = [50,51,52,53,54,511,512,513,514,521,522,523,524,525,526,527];
var result = [],
lastVal = -1;
while(arr.length) {
var currentIndex = arr.length - 1;
var currentValue = arr[currentIndex];
var c = Math.floor(currentValue/10);
if (c !== lastVal) {
lastVal = c;
result.push([currentValue]);
}else{
result[result.length-1].push(currentValue);
}
arr.splice(currentIndex, 1);
}
result.forEach(function(arr){ arr.reverse(); });
console.log(result);
Here's a solution using Ramda.js
const x = [50,51,52,53,54,511,512,513,514,521,522,523,524,525,526,527]
const f = R.pipe(
R.sortBy(R.identity),
R.groupWith(R.pipe(R.subtract, Math.abs, R.equals(1)))
)
console.log(f(x))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>

Conditional from recursion returning undefined

My code will keep looping until the length of the customerTimeArray is zero.
When I console.log before the return line it outputs 10, which is the correct answer.
function Supermarket() {
this.customerTimeArray;
this.currentTillers = [];
this.runningTime = 0;
}
Supermarket.prototype.queueTime = function(customerTimeArray, numberOfTills) {
this.customerTimeArray = customerTimeArray;
if (customerTimeArray.length === 0) {
return this.runningTime;
}
this.currentTillers = this.customerTimeArray.splice(0, numberOfTills);
this.deductLowestToAll(this.currentTillers);
this.queueTime(this.customerTimeArray, numberOfTills);
};
Supermarket.prototype.deductLowestToAll = function(array) {
var newArray = [];
var lowest = Math.min.apply(null, array);
array.forEach(element => {
newArray.push(element - lowest);
if (element === lowest) {
this.runningTime += lowest;
newArray.pop(element);
}
});
this.currentTillers = newArray;
};
supermarket = new Supermarket();
supermarket.queueTime([1, 2, 3, 4], 1);

Get the index of a multidimensional array with the value of a given string in javascript

I have this array,
var arr = [["present",["John","Josh","Jay"]],["absent",["May","Mary","Mary Jane"]]];
var arr2 = [["J",["John","Josh","Jay"]],["M",["May","Mary","Mary Jane"]]];
And I want to get the data[0] of the array that have value of "Mary".
So in my example, value that I will get is "absent".
I want also to get the index of the array arr2 that have value of "Josh".
So in my second array, value that I will get is 0.
If possible to use underscore js, we can use it.
I tried to use _.contains() but failed.
Also these array is used in knockout js.
One other way of doing this job could be as follows;
var a1 = [["present",["John","Josh","Jay"]],["absent",["May","Mary","Mary Jane"]]],
a2 = [["J",["John","Josh","Jay"]],["M",["May","Mary","Mary Jane"]],["S",["Sally","Sam","Sammy Davis"]]],
getStatus = (a,n) => a.find(e => e[1].indexOf(n) !== -1)[0],
getIndex = (a,n) => a.findIndex(e => e[1].indexOf(n) !== -1);
console.log(getStatus(a1,"Mary"));
console.log(getIndex(a2,"Sammy Davis"));
var arr = [["present",["John","Josh","Jay"]],["absent",["May","Mary","Mary Jane"]]];
var arr2 = [["J",["John","Josh","Jay"]],["M",["May","Mary","Mary Jane"]]];
arr.forEach(function(e,i,a){
if(e[1].indexOf("Mary")>-1){
console.log(e[0])
}
});
arr2.forEach(function(e,i,a){
if(e[1].indexOf("Josh")>-1){
console.log(e[0])
}
});
First using filter() and second findIndex()
var arr = [["present",["John","Josh","Jay"]],["absent",["May","Mary","Mary Jane"]]];
var result1 = arr.filter(x => x[1].indexOf("Mary") !== -1)[0][0];
console.log(result1); // absent
var arr2 = [["J",["John","Josh","Jay"]],["M",["May","Mary","Mary Jane"]]];
var result2 = arr.findIndex(x => x[1].indexOf("Josh") !== -1);
console.log(result2); // 0
If your data set isn't really huge you can store two map objects in memory to quickly access values. Note that this won't work for duplicate names.
The benefit of this approach is that you only have to loop through each array once. If you use any method based on indexOf, you'll loop through your data every time you retrieve a value.
var arr = [["present",["John","Josh","Jay"]],["absent",["May","Mary","Mary Jane"]]];
var arr2 = [["J",["John","Josh","Jay"]],["M",["May","Mary","Mary Jane"]]];
var makeKeyMap = function(arr) {
return arr.reduce(function(map, data) {
data[1].forEach(function(key) {
map[key] = data[0];
});
return map;
}, {});
};
var makeIndexMap = function(arr) {
return arr.reduce(function(map, data, index) {
data[1].forEach(function(key) {
map[key] = index;
});
return map;
}, {});
};
var arrMap = makeKeyMap(arr);
var arr2Map = makeIndexMap(arr2);
console.log(arrMap["Mary"]);
console.log(arr2Map["Josh"]);
Edit: a performance test
var myTestData = createTestData();
var randomNameToFind = (function() {
var namesToFind = ["Aileen","Christina","Donna","Judith","Mandy","Sandra","Dawn","Tracey","Mhairi","Victoria","Carolyn","Gayle","Maria","Valerie"];
return function() {
return namesToFind[Math.floor(Math.random() * namesToFind.length)];
}
}());
console.log("Finding the number index for a random name out of 800 names, 10000 times:");
console.time("using index of approach");
var usingIndexOf = (a,n) => a.findIndex(e => e[1].indexOf(n) !== -1);
var results = [];
for (var i = 0; i < 10000; i += 1) {
results.push(usingIndexOf(myTestData, randomNameToFind()));
}
console.timeEnd("using index of approach");
console.time("using map approach");
var makeIndexMap = function(arr) {
return arr.reduce(function(map, data, index) {
data[1].forEach(function(key) {
map[key] = index;
});
return map;
}, {});
};
var myMap = makeIndexMap(myTestData);
results = [];
for (var j = 0; j < 10000; j += 1) {
results.push(myMap[randomNameToFind()]);
}
console.timeEnd("using map approach");
console.log("index map size: " + sizeof(myMap) + " bytes");
// Random data generation code below
function createTestData() {
var names = ["Nicola","Karen","Fiona","Susan","Claire","Sharon","Angela","Gillian","Julie","Michelle","Jacqueline","Amanda","Tracy","Louise","Jennifer","Alison","Sarah","Donna","Caroline","Elaine","Lynn","Margaret","Elizabeth","Lesley","Deborah","Pauline","Lorraine","Laura","Lisa","Tracey","Carol","Linda","Lorna","Catherine","Wendy","Lynne","Yvonne","Pamela","Kirsty","Jane","Emma","Joanne","Heather","Suzanne","Anne","Diane","Helen","Victoria","Dawn","Mary","Samantha","Marie","Kerry","Ann","Hazel","Christine","Gail","Andrea","Clare","Sandra","Shona","Kathleen","Paula","Shirley","Denise","Melanie","Patricia","Audrey","Ruth","Jill","Lee","Leigh","Catriona","Rachel","Morag","Kirsten","Kirsteen","Katrina","Joanna","Lynsey","Cheryl","Debbie","Maureen","Janet","Aileen","Arlene","Zoe","Lindsay","Stephanie","Judith","Mandy","Jillian","Mhairi","Barbara","Carolyn","Gayle","Maria","Valerie","Christina","Marion","Nicola","Karen","Susan","Claire","Fiona","Angela","Sharon","Gillian","Julie","Jennifer","Michelle","Louise","Lisa","Amanda","Donna","Tracy","Alison","Elaine","Jacqueline","Sarah","Caroline","Elizabeth","Laura","Lynn","Deborah","Lesley","Margaret","Joanne","Pauline","Lorraine","Carol","Kirsty","Yvonne","Lorna","Emma","Lynne","Tracey","Heather","Catherine","Pamela","Helen","Linda","Jane","Anne","Kerry","Suzanne","Wendy","Victoria","Diane","Mary","Dawn","Clare","Gail","Paula","Ann","Shona","Hazel","Christine","Andrea","Samantha","Marie","Lynsey","Sandra","Denise","Lee","Kelly","Gayle","Debbie","Jill","Kathleen","Patricia","Joanna","Catriona","Shirley","Ruth","Zoe","Leigh","Rachel","Melanie","Kirsteen","Aileen","Christina","Janet","Katrina","Stephanie","Audrey","Kirsten","Arlene","Maureen","Morag","Marion","Mhairi","Allison","Cheryl","Maria","Kim","Anna","Lindsay","Rebecca","Katherine","Mandy","Nicola","Karen","Claire","Angela","Fiona","Susan","Jennifer","Julie","Gillian","Michelle","Sharon","Sarah","Louise","Donna","Laura","Amanda","Alison","Lisa","Caroline","Kirsty","Jacqueline","Elaine","Lesley","Lynn","Deborah","Elizabeth","Joanne","Emma","Tracy","Lorraine","Lynne","Margaret","Heather","Carol","Lorna","Pauline","Kelly","Helen","Catherine","Linda","Victoria","Suzanne","Kerry","Pamela","Lee","Wendy","Jane","Yvonne","Tracey","Anne","Clare","Mary","Diane","Christine","Lynsey","Samantha","Shona","Andrea","Marie","Gail","Melanie","Dawn","Ann","Paula","Jill","Ruth","Leigh","Hazel","Debbie","Joanna","Denise","Lindsay","Gayle","Patricia","Catriona","Kathleen","Sandra","Leanne","Stephanie","Rachel","Katrina","Shirley","Kirsteen","Janet","Arlene","Zoe","Jillian","Anna","Judith","Mhairi","Natalie","Audrey","Carolyn","Morag","Aileen","Cheryl","Rebecca","Allison","Barbara","Mandy","Claire","Nicola","Karen","Angela","Gillian","Fiona","Jennifer","Laura","Susan","Julie","Michelle","Lisa","Sharon","Louise","Sarah","Tracy","Donna","Kelly","Kirsty","Amanda","Alison","Joanne","Caroline","Emma","Jacqueline","Elaine","Elizabeth","Lynne","Lesley","Deborah","Kerry","Victoria","Carol","Catherine","Lynn","Pauline","Margaret","Lorna","Lynsey","Lorraine","Linda","Suzanne","Tracey","Heather","Yvonne","Jane","Dawn","Mary","Helen","Anne","Wendy","Lee","Pamela","Jill","Lindsay","Clare","Christine","Diane","Leigh","Samantha","Shona","Joanna","Ruth","Debbie","Gail","Marie","Andrea","Paula","Kathleen","Catriona","Katrina","Denise","Melanie","Ann","Sandra","Gayle","Hazel","Jillian","Stephanie","Rachel","Kim","Natalie","Katherine","Patricia","Leanne","Cheryl","Mhairi","Morag","Arlene","Zoe","Kathryn","Aileen","Ashley","Judith","Anna","Frances","Janet","Lucy","Vicky","Christina","Kirsten","Rebecca","Nicola","Claire","Laura","Karen","Michelle","Louise","Jennifer","Fiona","Lisa","Gillian","Angela","Julie","Susan","Sarah","Kelly","Donna","Sharon","Emma","Caroline","Alison","Joanne","Tracy","Kirsty","Lynne","Amanda","Elaine","Jacqueline","Lesley","Kerry","Elizabeth","Lynn","Margaret","Deborah","Catherine","Heather","Lorna","Yvonne","Carol","Lorraine","Suzanne","Lynsey","Victoria","Helen","Linda","Pauline","Dawn","Anne","Jane","Tracey","Clare","Mary","Diane","Jill","Denise","Lee","Leanne","Christine","Shona","Pamela","Samantha","Paula","Joanna","Debbie","Stacey","Hazel","Cheryl","Lindsay","Gail","Rachel","Marie","Ann","Catriona","Andrea","Ruth","Kathryn","Katrina","Mhairi","Wendy","Leigh","Gayle","Melanie","Sandra","Stephanie","Anna","Jillian","Amy","Carolyn","Patricia","Carrie","Natalie","Kathleen","Lyndsey","Ashley","Rebecca","Vicky","Christina","Lindsey","Katherine","Arlene","Sara","Laura","Claire","Nicola","Lisa","Louise","Michelle","Fiona","Karen","Gillian","Jennifer","Emma","Angela","Susan","Kelly","Julie","Donna","Sarah","Kirsty","Sharon","Joanne","Amanda","Tracy","Alison","Elizabeth","Caroline","Elaine","Jacqueline","Lynne","Leanne","Deborah","Lesley","Lorraine","Victoria","Lynn","Pamela","Kerry","Lynsey","Lorna","Carol","Margaret","Heather","Helen","Catherine","Suzanne","Tracey","Yvonne","Cheryl","Linda","Pauline","Debbie","Jane","Dawn","Clare","Lindsay","Mary","Shona","Anne","Rachel","Jill","Christine","Natalie","Samantha","Diane","Lee","Wendy","Joanna","Paula","Marie","Ann","Denise","Catriona","Gayle","Hazel","Kathleen","Stacey","Gail","Ashley","Andrea","Ruth","Anna","Jillian","Leigh","Katrina","Stephanie","Mhairi","Katherine","Sandra","Lyndsey","Christina","Lucy","Patricia","Carrie","Rebecca","Kathryn","Lyndsay","Melanie","Amy","Sara","Arlene","Kirsten","Laura","Claire","Lisa","Nicola","Louise","Karen","Fiona","Jennifer","Michelle","Emma","Sarah","Gillian","Kelly","Susan","Angela","Donna","Kirsty","Julie","Pamela","Joanne","Caroline","Amanda","Tracy","Sharon","Lynne","Elaine","Deborah","Jacqueline","Alison","Lynsey","Victoria","Kerry","Leanne","Lorraine","Lesley","Elizabeth","Lorna","Catherine","Lynn","Suzanne","Heather","Helen","Lindsay","Margaret","Clare","Cheryl","Debbie","Pauline","Dawn","Carol","Mary","Natalie","Linda","Jane","Diane","Stacey","Carrie","Yvonne","Rebecca","Christine","Marie","Charlene","Rachel","Anne","Tracey","Jill","Samantha","Ashley","Paula","Joanna","Stephanie","Andrea","Shona","Denise","Anna","Hazel","Katrina","Ruth","Gayle","Lee","Sara","Catriona","Kathryn","Leigh","Mhairi","Wendy","Amy","Jillian","Katherine","Gail","Linsey","Christina","Lucy","Melanie","Sandra","Ann","Kathleen","Shelley","Kirsten","Kim","Lyndsey","Laura","Claire","Lisa","Nicola","Emma","Louise","Jennifer","Michelle","Sarah","Fiona","Karen","Gillian","Kirsty","Donna","Kelly","Pamela","Susan","Julie","Angela","Amanda","Lynsey","Sharon","Lynne","Deborah","Joanne","Victoria","Caroline","Alison","Leanne","Gemma","Elaine","Jacqueline","Lesley","Elizabeth","Lorraine","Kerry","Heather","Debbie","Catherine","Lynn","Lorna","Tracy","Suzanne","Yvonne","Cheryl","Natalie","Margaret","Lindsay","Diane","Helen","Pauline","Ashley","Rachel","Clare","Carol","Christine","Linda","Dawn","Rebecca","Stephanie","Jill","Tracey","Jane","Stacey","Paula","Shona","Anna","Charlene","Anne","Marie","Catriona","Samantha","Joanna","Ruth","Andrea","Mary","Denise","Kim","Mhairi","Hazel","Lauren","Amy","Kathryn","Carrie","Lyndsey","Lucy","Gail","Katherine","Christina","Linsey","Wendy","Katrina","Kimberley","Ann","Lee"];
var nameMap = names.reduce((map, n) => {
map[n[0]] = map[n[0]] || [];
map[n[0]].push(n);
return map;
}, {});
var testData = Object.keys(nameMap)
.sort()
.reduce((res, k) => {
res.push([k, nameMap[k]]);
return res;
}, []);
return testData;
};
<script src="http://code.stephenmorley.org/javascript/finding-the-memory-usage-of-objects/sizeof.compressed.js"></script>

Categories

Resources